I think I'm messing up Regex or do not understand ...
# getting-started
j
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
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
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
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
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.