How do I replace ” with \”.
Here is what im trying :
def main(args:Array[String]) = {
val line:String = "replace \" quote";
println(line);
val updatedLine = line.replaceAll("\"" , "\\\"");
println(updatedLine);
}
output :
replace " quote
replace " quote
The output should be :
replace " quote
replace \" quote
Two more
\\does the job:The problem here is that there are two ‘layers’ escaping the strings. The first layer is the compiler, which we can easily see in the REPL:
The second layer is the regular expression interpreter. This one is harder to see, but can be seen by applyin your example:
What the reg. exp. interpreter really receives is \”, which is interpreted as only “. So, we need the reg. exp. to receive \\”. To make the compiler give us \ we need to write \\.
Let’s see the unescaping:
It can be a bit confusing despite being very straight forward.
As pointed by @sschaef, another alternative it to use “”” triple-quoting, strings in this form aren’t unescaped by the compiler: