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
You can use “replace[d] with” in any situation, but it's safest to only use “replaced by” in passive sentences. “The humans were replaced by computers.” “We will be replaced by computers.” It sounds unnatural to say, “Replace a banana by an orange.” Use “with.”
Paper bags have been largely replaced by plastic bags. She was hired to replace the previous manager. I replaced the old rug with a new one. They recently replaced the old phone system.
The sentence pattern is: substitute A for B, and means that in the end A is used instead of B. Having something else (B) being used or placed in its place. The preposition with is used in this meaning. The sentence pattern is: substitute A with B, and the sentence means that in the end B is used instead of A.
Some common synonyms of replace are displace, supersede, and supplant. While all these words mean "to put out of a usual or proper place or into the place of another," replace implies a filling of a place once occupied by something lost, destroyed, or no longer usable or adequate. replaced the broken window.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With