gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 00:51:29 25 4
gpt4 key购买 nike

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

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

最佳答案

MatchResult对象具有 range属性:

The range of indices in the original string where match was captured.

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

A short demo显示整个单词的第一个匹配范围 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'

关于android - 在 Kotlin 中使用正则表达式获取字符串中模式的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59201043/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com