Frede Veloz
Frede Veloz

Reputation: 83

Find position of every ocurrence of a pattern in Kotlin

I have this large chunk of text in Kotlin. I created a regex pattern to find some substrings within it. Using the findAll function I found every instance that matched the regex pattern. However, I want the exact integer position of every matched instance within the original text. Is there a way to get that directly?

Upvotes: 2

Views: 1806

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170839

Regex.findAll returns a Sequence<MatchResult>, and MatchResult has range, so

Regex(yourPattern).findAll(someString).map { it.range.start }

will return the sequence of starting indices.

Upvotes: 7

Related Questions