在 Kotlin 中使用正则表达式获取字符串中模式的索引

Vel*_*glu 7 regex android kotlin

我想用 kotlin 搜索字符串中的特定模式。

正则表达式类是否提供字符串中模式的位置(字符串中的索引)?

Wik*_*żew 7

MatchResult对象具有range属性:

捕获匹配的原始字符串中的索引范围。

此外,MatchGroup也有一个range属性。

一个简短的演示,显示整个单词的第一个匹配的范围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'
Run Code Online (Sandbox Code Playgroud)