Simon Simon - 1 month ago 10
Scala Question

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.

Answer

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
Comments