How do I replace \" with \\\".
Here is what im trying :
def main(args:Array[String]) = {
val line:String = \"replace \\\" quote\";
println
Use "replaceAllLiterally" method of StringOps class. This replaces all literal occurrences of the argument:
scala> val line:String = "replace \" quote"
line: String = replace " quote
scala> line.replaceAllLiterally("\"", "\\\"")
res8: String = replace \" quote
@pedrofurla nicely explains why you saw the behavior you did. Another solution to your problem would be to use a raw string with scala's triple-quote character. Anything between a pair of triple-quotes is treated as a raw string with no interpretation by the Scala compiler. Thus:
scala> line.replaceAll("\"", """\\"""")
res1: String = replace \" quote
Used in conjunction with stripMargin
, triple-quotes are a powerful way to embed raw strings into your code. For example:
val foo = """
|hocus
|pocus""".stripMargin
yields the string: "\nhocus\npocus"
Two more \\
does the job:
scala> line.replaceAll("\"" , "\\\\\"");
res5: java.lang.String = replace \" quote
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:
scala> "\""
res0: java.lang.String = "
scala> "\\"
res1: java.lang.String = \
scala> "\\\""
res2: java.lang.String = \"
scala> val line:String = "replace \" quote";
line: String = replace " quote
The second layer is the regular expression interpreter. This one is harder to see, but can be seen by applyin your example:
scala> line.replaceAll("\"" , "\\\"");
res5: java.lang.String = replace " quote
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:
scala> line.replaceAll("\"" , """\\"""");
res6: java.lang.String = replace \" quote