1

在 Javascript 中搜索 RegExp 模式以验证电子邮件地址时,我发现 Facebook 从此处使用的模式。

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

有人可以向我解释这种模式是如何工作的吗?我知道它正在三个位置寻找“单词字符”以及一个“@”字符。但是一个很好的解释将有助于我理解这一点。

4

1 回答 1

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!.%+\-]+@[\w\-]+(?:\.[\w\-]+)+$/
于 2013-05-01T23:49:49.013 回答