0

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

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

^([\\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}$
4

1 回答 1

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
于 2013-01-10T17:33:20.907 回答