Calebe
Calebe

Reputation: 817

Replacing the 1st regex-match group instead of the 0th

I was expecting this

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

println(string.replace(regex, ""))

to result in this:

hello, world

Instead, it prints this:

hello world

I see that the replace function cares about the whole match. Is there a way to replace only the 1st group instead of the 0th one?

Upvotes: 2

Views: 7439

Answers (2)

Christian Kuka
Christian Kuka

Reputation: 119

You can retrieve the match range of the regular expression by using the groups property of MatchGroupCollection and then using the range as a parameter for String.removeRange method:

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

Upvotes: 1

Toto
Toto

Reputation: 91518

Add the comma in the replacement:

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

println(string.replace(regex, ","))

Or, if kotlin supports lookahead:

val string = "hello   , world"
val regex = Regex("""\s+(?=,)""")

println(string.replace(regex, ""))

Upvotes: 3

Related Questions