[`replace` function][2] in Kotlin has overloads for either raw string and regex patterns.
"Test me".replace("\\s+", " ")
This replaces raw string `\s+`, which is the problem.
"Test me".replace("\\s+".toRegex(), " ")
This line replaces multiple whitespaces with a single space.
Note the explicit [`toRegex()`][3] call, which makes a `Regex` from a `String`, thus specifying the overload with `Regex` as pattern.
There's also an overload which allows you to produce the replacement from the matches. For example, to replace them with the first whitespace encountered, use this:
"Test\n\n me".replace("\\s+".toRegex()) { it.value[0].toString() }
<hr>
By the way, if the operation is repeated, consider moving the pattern construction out of the repeated code for better efficiency:
val pattern = "\\s+".toRegex()
for (s in strings)
result.add(s.replace(pattern, " "))
[1]:
[To see links please register here]
[2]:
[To see links please register here]
[3]:
[To see links please register here]