java, regular expression, need to escape backslash in regex

前端 未结 4 639
予麋鹿
予麋鹿 2020-12-01 21:08

With reference to below question - String.replaceAll single backslashes with double backslashes

I wrote a test program, and I found that the result is true in both

4条回答
  •  醉梦人生
    2020-12-01 22:05

    Yes, there is a general guideline about escaping: Escape sequences in your Java source get replaced by the Java compiler (or some preprocessor eventually). The compiler will complain about any escape sequences it does not know, e.g. \s. When you write a String literal for a RegEx pattern, the compiler will process this literal as usual and replace all escape sequences with the according character. Then, when the program is executed, the Pattern class compiles the input String, that is, it will evaluate escape sequences another time. The Pattern class knows \s as a character class and will therefore be able to compile a pattern containing this class. However, you need to escape \s from the Java compiler which does not know this escape sequence. To do so, you escape the backslash resulting in \\s.

    In short, you always need to escape character classes for RegEx patterns twice. If you want to match a backslash, the correct pattern is \\\\ because the Java compiler will make it \\ which the Pattern compiler will recognize as the escaped backslash character.

提交回复
热议问题