How to write a regular expression to match this \" (a backslash then a quote)? Assume I have a string like this:
<a href=\"google.com\"> click to search </a>
I need to replace all the \" with a ", so the result would look like:
<a href="google.com"> click to search </a>
This one does not work: str.replaceAll("\\\"", "\"") because it only matches the quote. Not sure how to get around with the backslash. I could have removed the backslash first, but there are other backslashes in my string.
If you don’t need any of regex mechanisms like predefined character classes \d, quantifiers etc. instead of
replaceAllwhich expects regex usereplacewhich expects literalsBoth methods will replace all occurrences of targets, but
replacewill treat targets literally.BUT if you really must use regex you are looking for
\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\tto represent tabulator.That is why you also need to escape
\there.In short you need to escape
\twice:\\"\\\\"