首页 > 正则表达式匹配圆点(".")的疑问

正则表达式匹配圆点(".")的疑问

如果要匹配“.”为什么用\\.如果用\.会报错


如果是Java的话,反斜杠本身是特殊字符。这个问题应该和正则表达式没有关系,是java的String字符串的问题。

如果定义一个字符串:

String s = "\t";

那么这时候\t是一个整体,表示tab。

如果这样定义:

String s = "\\t";

这个时候字符串s中存储了两个(如果不需要像C那样考虑结束符之类的话,我不知道有没有结束符)字符,\t

回到问题。对于

String s = "\\w{3,20}@(qq|mail|163)\.com"

java认为\.是一个整体,会对其转义。但是没有发现对应的转义符。(如第一个回答列出来的那些转义符,其中没有\.),那么就报错了。

对于第二个,意义也就很清楚了。
第二个实际上参与正则表达式匹配的字符串是

\w{3,20}@(qq|mail|163)\.com

注意第一个双反斜杠,是一样处理的。


https://docs.oracle.com/javase/tutorial/java/data/characters.html
Escape Sequences
A character preceded by a backslash (\) is an escape sequence and has special meaning to the compiler. The following table shows the Java escape sequences:

Escape Sequences
\t Insert a tab in the text at this point.
\b Insert a backspace in the text at this point.
\n Insert a newline in the text at this point.
\r Insert a carriage return in the text at this point.
\f Insert a formfeed in the text at this point.
\' Insert a single quote character in the text at this point.
\" Insert a double quote character in the text at this point.
\\ Insert a backslash character in the text at this point.
When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. To print the sentence

She said "Hello!" to me.
you would write

System.out.println("She said \"Hello!\" to me.");

我用php测试了下,.前面加一个\和加两个\\都能正确匹配,不报错,甚至不加\也可以,同求解答

【热门文章】
【热门文章】