正则表达式的电子邮件地址不接受.cat

时间:2013-01-10 17:24:37

标签: regex

我从来没有真正研究过正则表达式,所以不要真正解决它

我有以下用于测试电子邮件地址的正则表达式

^([\\w]+)(\\.[\\w]+)*@([\\w\\-]+\\.){1,5}([A-Za-z]){2,4}$

当我输入example@example.cat时,它会失败,但当我输入example@example.com时,它有效......任何人都可以解释为什么会这样吗?

修改

一直在查看代码,这个正则表达式是否会因上述电子邮件地址而失败?

^\\w[-._\\w]*\\w@\\w[-._\\w]*\\w\\.\\w{2,6}$

1 个答案:

答案 0 :(得分:3)

.cat的正则表达式不会失败,但匹配.com您必须遇到导致您看到的行为的其他问题,以下是对regex的解释:

^([\w]+)(\.[\w]+)*@([\w-]+\.){1,5}([A-Za-z]){2,4}$/

^ Start of string

1st Capturing group ([\w]+) 
Char class [\w] infinite to 1 times matches one of the following chars: \w
\w Word character [a-zA-Z_\d] 

2nd Capturing group (\.[\w]+) infinite to 0 times 
\. Literal .
Char class [\w] infinite to 1 times matches one of the following chars: \w
\w Word character [a-zA-Z_\d] 
@ Literal @

3rd Capturing group ([\w-]+\.) 5 to 1 times 
Char class [\w-] infinite to 1 times matches one of the following chars: \w-
\w Word character [a-zA-Z_\d] 
\. Literal .

4th Capturing group ([A-Za-z]) 4 to 2 times 
Char class [A-Za-z] matches one of the following chars: A-Za-z

$ End of string

第二个也会接受两个给出正确的转义(在大多数语言中,双反斜杠会导致两个不匹配):

/^\w[-._\w]*\w@\w[-._\w]*\w\.\w{2,6}$/

^ Start of string

\w Word character [a-zA-Z_\d] 
Char class [-._\w] infinite to 0 times matches one of the following chars: -._\w
\w Word character [a-zA-Z_\d] 
\w Word character [a-zA-Z_\d] 

@ Literal @

\w Word character [a-zA-Z_\d] 
Char class [-._\w] infinite to 0 times matches one of the following chars: -._\w

\w Word character [a-zA-Z_\d] 
\w Word character [a-zA-Z_\d] 

\. Literal .

\w 6 to 2 times Word character [a-zA-Z_\d] 

$ End of string
相关问题