2013-05-01 101 views
1

當在Javascript中搜索RegExp模式以驗證電子郵件地址時,我發現了一個從here使用的Facebook模式。Facebook註冊表格電子郵件驗證模式

function is_email(a){return /^([\w!.%+\-])[email protected]([\w\-])+(?:\.[\w\-]+)+$/.test(a);} 

有人請向我解釋這種模式是如何工作的嗎?我知道它正在尋找三個位置的「單詞字符」以及一個「@」字符。但一個很好的解釋對我來說很有幫助,可以理解這一點。

+2

以下是兩個網站,它們對正則表達式模式產生或多或少有用的解釋:http://www.regexper.com/和http://regex101.com/ – 2013-05-01 13:10:36

+1

謝謝!這樣可行。如果你想把它寫成答案,我很樂意接受它。 – user 2013-05-01 13:52:23

回答

0

有兩個網站(我知道),其中生成正則表達式模式的解釋。

這是我自己的方式解釋:

^  # anchor the pattern to the beginning of the string; this ensures that 
     # there are no undesired characters before the email address, as regex 
     # matches might well be substrings otherwise 
(  # starts a group (which is unnecessary and incurs overhead) 
    [\w!.%+\-] 
     # matches a letter, digit, underscore or one of the explicitly mentioned 
     # characters (note that the backslash is used to escape the hyphen 
     # although that is not required if the hyphen is the last character) 
)+  # end group; repeat one or more times 
@  # match a literal @ 
(  # starts another group (again unnecessary and incurs overhead) 
    [\w\-] # match a letter, digit, underscore or hyphen 
)+  # end group; repeat one or more times 
(?:  # starts a non-capturing group (this one is necessary and, because 
     # capturing is suppressed, this one does not incur any overhead) 
    \.  # match a literal period 
    [\w\-] # match a letter, digit, underscore or hyphen 
    +  # one or more of those 
)+  # end group; repeat one or more times 
$  # anchor the pattern to the end of the string; analogously to^

所以,這將是一個稍微優化版本:

/^[\w!.%+\-][email protected][\w\-]+(?:\.[\w\-]+)+$/