java, regular expression, need to escape backslash in regex

前端 未结 4 657
予麋鹿
予麋鹿 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:03

    There are two interpretations of escape sequences going on: first by the Java compiler, and then by the regexp engine. When Java compiler sees two slashes, it replaces them with a single slash. When there is t following a slash, Java replaces it with a tab; when there is a t following a double-slash, Java leaves it alone. However, because two slashes have been replaced by a single slash, regexp engine sees \t, and interprets it as a tab.

    I think that it is cleaner to let the regexp interpret \t as a tab (i.e. write "\\t" in Java) because it lets you see the expression in its intended form during debugging, logging, etc. If you convert Pattern with \t to string, you will see a tab character in the middle of your regular expression, and may confuse it for other whitespace. Patterns with \\t do not have this problem: they will show you a \t with a single slash, telling you exactly the kind of whitespace that they match.

提交回复
热议问题