I want to search a string for a specific pattern with kotlin.
Do the regular expression classes provide the positions (indexes within the string) of the pattern within the string?
The MatchResult object has the range property:
The range of indices in the original string where match was captured.
Also, MatchGroup has a range property, too.
A short demo showing the range of the first match of a whole word long:
val strs = listOf("Long days become shorter","winter lasts longer")
val pattern = """(?i)\blong\b""".toRegex()
strs.forEach { str ->
val found = pattern.find(str)
if (found != null) {
val m = found?.value
val idx = found?.range
println("'$m' found at indexes $idx in '$str'")
}
}
// => 'Long' found at indexes 0..3 in 'long days become shorter'
MatchResultobject has therangeproperty: "The range of indices in the original string where match was captured.". Also,MatchGrouphas arangeproperty, too.