I want to replace all
\ with \\ and all
" with \"
in a String.
I use this line of code:
text = text.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"");
But i have PatternSyntaxException
Why?
The arguments to replaceAll get processed twice: first by the
compiler, then by the Pattern (first argument) and Matcher (second
argument) classes, which do the actual matching and replacing. Both
of those classes also treat the backslash as an escape character. So,
to match a literal backslash character, or to insert one into the
replacement string, you have to double it, then double it again. So
replacing a single backslash with a double backslash looks like this:
text = text.replaceAll("\\\\", "\\\\\\\\");
The double-quote character, OTOH, has to be escaped for the compiler,
but it isn't special to the regex classes, so you only need one
backslash to escape it. Of course, to add a backslash in front of it,
you have to use four of them, plus the one to escape the quote:
text = text.replaceAll("\"", "\\\\\"");
Instead of doing in two passes, though, you can use the power of
regexes to do it in one:
text = text.replaceAll("[\"\\\\]", "\\\\$0");
The regex, "[\"\\\\]", is a character class that matches either a
quote or a backslash, and the $0 in the second argument gets replaced
with whatever was matched by the regex. For more info, check out this
site:
http://www.regular-expressions.info/