https://kotlinlang.org logo
#getting-started
Title
# getting-started
j

Jonathan Kolberg

12/03/2023, 7:20 AM
I think I'm messing up Regex or do not understand it enought. When I have
val result = "44".toRegex().findAll("14446")
why is result only of length one, in my understanding it should match
1$44$45
and
14$44$5
. Here I marked the match visually with
$
e

ephemient

12/03/2023, 7:20 AM
findAll
does not return overlapping matches
you can see, for example, that
Copy code
".+".toRegex().findAll("abc")
only returns the single run of
abc
, not
abc
bc
c
j

Jonathan Kolberg

12/03/2023, 7:23 AM
Hm how do I find overlapping matches then, is there something in the std? I could of cause check for every suffix, if it starts with the pattern, but that seems tedious
e

ephemient

12/03/2023, 7:40 AM
nothing in stdlib, but you can do it yourself with a loop moving
find(startIndex=)
to
match.range.first + 1
e.g.
Copy code
generateSequence(regex.find(str)) { regex.find(str, startIndex = it.range.first + 1) }
👍 1
j

Johann Pardanaud

12/03/2023, 9:50 AM
Here’s a clever regex solution based on capturing groups and lookahead assertions: https://stackoverflow.com/a/11430936/1513045
I am unable to try this in Kotlin at the moment, but it could work.