Raymond Chenon
Raymond Chenon

Reputation: 12712

Scala replace " by \"

How to replace the double quote by \":

val s = """I am "groot"."""

so the output will be """I am \"groot\"."""

I tried with but no luck

s.replaceAll('"', '\"')

Upvotes: 0

Views: 421

Answers (3)

Silvio Mayolo
Silvio Mayolo

Reputation: 70347

So @Tanjin provides the correct solution. However, the reason your solution does not work is this.

s.replaceAll('"', '\"')

Backslashes have special meaning in string and character literals, so '\"' compiles down to just the quote character. Running in the REPL will show you this

scala> '\"'
res2: Char = "

Meanwhile, using triple-quote strings disables this behavior.

scala> """\""""
res3: String = \"

Upvotes: 2

Tanjin
Tanjin

Reputation: 2452

How does this work:

s.replace(""""""", """\"""")

Upvotes: 1

igorpcholkin
igorpcholkin

Reputation: 967

Try this way:

s.replaceAll("\"", "\\\\\"")

Upvotes: 1

Related Questions