How to replace all numbers with literal \ d in scala?

I want to write a function to replace all numbers in a string with a literal \d. My code is:

val r = """\d""".r
val s = r.replaceAllIn("123abc", """\d""")
println(s)

I expect the result to be \d\d\dabc, but get:

dddabc

Then I change my code (line 2) to:

val s = r.replaceAllIn("123abc", """\\d""")

Now the result is correct: \d\d\dabc

But I don’t understand why the method replaceAllInconverts the string instead of using it directly?


In my previous code was toList, now I want. I just updated a question. Thanks to everyone.

+3
source share
2 answers

Just uninstall toList.

val r = """\d""".r
val list = r.replaceAllIn("123abc", """\\d""")
println(list)

String(implicitly, through WrappedString, converted to) Seq[Char]. If you call toList, you will have List[Char].

+1
source

Scala Regex java.util.regex ( , JVM). , replaceAll Java-, :

, (\) ($) , . , , .

+1

Source: https://habr.com/ru/post/1795216/


All Articles