Reputation: 6462
Is there a way to replace some string in a text using the original matched values?
For instance, I would like to replace all the integers by decimals, as in the following example:
"hello 45 hello 4 bye" --> "hello 45.0 hello 4.0 bye"
I could match all the numbers with findAllIn
and after replace them but I would like to know if there is a better solution.
Upvotes: 0
Views: 996
Reputation: 37832
Using RegularExpressions, you can use $1
to get the result of the first capturing group (in parenthesis):
val regex = "(\\d+)".r
val text = "hello 45 hello 4 bye"
val result = regex.replaceAllIn(text, "$1.0")
// result: String = hello 45.0 hello 4.0 bye
Upvotes: 2
Reputation: 6172
Use the overload of replaceAllIn
that takes a replacer
function:
Upvotes: 0