替换第一个正则expression式匹配组而不是第0个

我期待着这一点

val string = "hello , world" val regex = Regex("""(\s+)[,]""") println(string.replace(regex, "")) 

导致这样的结果:

 hello, world 

相反,它打印这个:

 hello world 

我看到replacefunction关心整个比赛。 有没有办法只更换第一组而不是第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, "")) 

您可以使用MatchGroupCollection的groups属性检索正则expression式的匹配范围,然后使用范围作为String.removeRange方法的参数:

 val string = "hello , world" val regex = Regex("""(\s+)[,]""") val result = string.removeRange(regex.find(string)!!.groups[1]!!.range)