我就期待这个
val string = "hello , world"
val regex = Regex("""(\s+)[,]""")
println(string.replace(regex, ""))
结果是:
hello, world
相反,它打印:
hello world
我发现replace
函数关心整个匹配。有没有办法只替换第 1 组而不是第 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, ""))
关于regex - 替换第 1 个正则表达式匹配组而不是第 0 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48486429/