Java - escaping double quotes in string from file

You need to use 4 backslashes to denote one literal backslash in the replacement pattern:

content=content.replaceAll("\"","\\\\\"");

Here, \\\\ means a literal \ and \" means a literal ".

More details at Java String#replaceAll documentation:

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll

And later in Matcher.replaceAll documentation:

Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.

Another fun replacement is replacing quotes with dollar sign: the replacement is "\\$". The 2 \s turn into 1 literal \ for the regex engine and it escapes the special character $ used to define backreferences. So, now it is a literal inside the replacement pattern.


You need to do :

String content = "some content with \" quotes.";
content = content.replaceAll("\"", "\\\\\"");

Why will this work?

\" represents the " symbol, while you need \".

If you add a \ as a prefix (\\") then you'll have to escape the prefix too, i.e. you'll have a \\\". This will now represent \", where \ is not the escaping character, but the symbol \.

However in the Java String the " character will be escaped with a \ and you will have to replace it as well. Therefore prefixing again with \\ will do fine:

x = x.replaceAll("\"", "\\\\\"");

Tags:

Java

Regex