Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why escaping double quote with single and triple backslashes in a Java regular expression yields identical results

Tags:

java

regex

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?

like image 980
RAHUL JAISWAL Avatar asked Oct 22 '25 16:10

RAHUL JAISWAL


1 Answers

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.

like image 127
Wiktor Stribiżew Avatar answered Oct 25 '25 05:10

Wiktor Stribiżew