Simon
Simon

Reputation: 6462

Scala: how to replace strings using the original matched values

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

Answers (2)

Tzach Zohar
Tzach Zohar

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

Related Questions