I want to escape " (double quotes) in a regex.
I found out that there is no difference whether I use \\\ or \, both yield the same correct result.
Why is it so? How can the first one give correct result?
To define a " char in a string literal in Java, you need to escape it for the string parsing engine, like "\"".
The " char is not a special regex metacharacter, so you needn't escape this character for the regex engine. However, you may do it:
A backslash may be used prior to a non-alphabetic character regardless of whether that character is part of an unescaped construct.
To define a regex escape a literal backslash is used, and it is defined with double backslash in a Java string literal, "\\":
It is therefore necessary to double backslashes in string literals that represent regular expressions to protect them from interpretation by the Java bytecode compiler.
So, both "\"" (a literal " string) and "\\\"" (a literal \" string) form a regex pattern that matches a single " char.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With