Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 替换第一个正则表达式匹配组而不是第0个_Regex_Kotlin - Fatal编程技术网

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