If you don’t need any of regex mechanisms like predefined character classes \d, quantifiers etc. instead of replaceAll
which expects regex use replace
which expects literals
str = str.replace("\\\"","\"");
Both methods will replace all occurrences of targets, but replace
will treat targets literally.
BUT if you really must use regex you are looking for
str = str.replaceAll("\\\\\"", "\"")
\
is special character in regex (used for instance to create \d
– character class representing digits). To make regex treat \
as normal character you need to place another \
before it to turn off its special meaning (you need to escape it). So regex which we are trying to create is \\
.
But to create string literal representing text \\
so you could pass it to regex engine you need to write it as four \
("\\\\"
), because \
is also special character in String literals (part of code written using "..."
) since it can be used for instance as \t
to represent tabulator.
That is why you also need to escape \
there.
In short you need to escape \
twice:
- in regex
\\
- and then in String literal
"\\\\"