If I have string a"b"c", but I want to get a\"b\"c\", I would naturally write
String t = "a\"b\"c\"";
t = t.replaceAll("\"", "\\\"");
However, that results in the same string, a"b"c". The correct way is
t.replaceAll("\"", "\\\\\"");
Why?
replaceAlluses regular expressions for both the pattern and the replacement – both of which require backslashes to be escaped. So the regex replacement pattern you want for the second argument is:Now because both
\and"in Java string literals also need escaping, that means each of those characters needs an extra backslash. Add the quotes, and you’ve got:which is what you’ve got in your source.
It’s simpler if you just use
String.replacewhich doesn’t use regular expressions. That way you’re only trying to provide this string (not string literal) as the second argument:After escaping and turning into a string literal, that becomes:
which still isn’t great, but it’s at least better.
An alternative is to use
replaceAllbut withMatcher.quoteReplacement:Personally I’d just use
replace()though. You don’t want regular expression replacements, after all.