8

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?

1
  • 1
    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. Commented Dec 5, 2019 at 18:24

1 Answer 1

8

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'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.