Reputation: 63415
I'd like to escape certain characters preceding them with a \
I came up with the following solution:
scala> val l = List(".", "+", " ")
scala> val x = "hola.vamos a+escapar"
scala> l.foldRight(x){ (char, text) => text.replaceAll("""\""" + char, """\\""" + char) }
res1: java.lang.String = hola\.vamos\ a\+escapar
But I'm pretty sure there must be a way to use a regular expression to achieve it, but I don't know how to reference the matching text...
Upvotes: 1
Views: 272
Reputation: 33019
"hola.vamos a+escapar".replaceAll("([.+ ])", "\\\\$1")
or
"hola.vamos a+escapar".replaceAll("([.+ ])", """\\$1""")
depending on if you prefer lots of quotes or lots of backslashes.
Upvotes: 4