Regex 替换第一个正则表达式匹配组而不是第0个
我正期待着呢Regex 替换第一个正则表达式匹配组而不是第0个,regex,kotlin,Regex,Kotlin,我正期待着呢 val string = "hello , world" val regex = Regex("""(\s+)[,]""") println(string.replace(regex, "")) 为此: hello, world 而是打印以下内容: hello world 我看到replace函数关心整个匹配。有没有办法只替换第一组而不是第0组?在替换中添加逗号: val string = "hello , world" val regex = Regex("""(
val string = "hello , world"
val regex = Regex("""(\s+)[,]""")
println(string.replace(regex, ""))
为此:
hello, world
而是打印以下内容:
hello world
我看到
replace
函数关心整个匹配。有没有办法只替换第一组而不是第0组?在替换中添加逗号:
val string = "hello , world"
val regex = Regex("""(\s+)[,]""")
println(string.replace(regex, ","))
或者,如果kotlin支持前瞻:
val string = "hello , world"
val regex = Regex("""\s+(?=,)""")
println(string.replace(regex, ""))
在替换项中添加逗号:
val string = "hello , world"
val regex = Regex("""(\s+)[,]""")
println(string.replace(regex, ","))
或者,如果kotlin支持前瞻:
val string = "hello , world"
val regex = Regex("""\s+(?=,)""")
println(string.replace(regex, ""))
通过使用MatchGroupCollection的groups属性,然后将该范围用作String.removeRange方法的参数,可以检索正则表达式的匹配范围:
val string = "hello , world"
val regex = Regex("""(\s+)[,]""")
val result = string.removeRange(regex.find(string)!!.groups[1]!!.range)
通过使用MatchGroupCollection的groups属性,然后将该范围用作String.removeRange方法的参数,可以检索正则表达式的匹配范围:
val string = "hello , world"
val regex = Regex("""(\s+)[,]""")
val result = string.removeRange(regex.find(string)!!.groups[1]!!.range)
捕获文本的一部分有助于在替换模式中使用反向引用保持文本。您需要删除的内容不应被捕获。您可以使用
Regex(““\s+(,)””)
,然后使用.replace(Regex,“$1”)
。捕获文本的一部分有助于在替换模式中使用反向引用保留它。您需要删除的内容不应被捕获。您可以使用Regex(“\s+(,)””)
,然后使用。替换(Regex,“$1”)
。是的,Kotlin支持lookaheadsys,Kotlin支持lookaheads