2

我正在使用以下正则表达式来验证电子邮件:

^[a-zA-Z0-9!$'*+/\-_#%?^`&=~}{|]+(\.[a-zA-Z0-9!$'*+/\-_#%?^`&=~}{|]+)*@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-['&_\]]]+)(\.[\w-['&_\]]]+)*))(\]?)$

这在 C# 中工作正常,但在 JavaScript 中,它不起作用....是的,我用双反斜杠替换了每个反斜杠,如下所示:

^[a-zA-Z0-9!$'*+/\\-_#%?^`&=~}{|]+(\\.[a-zA-Z0-9!$'*+/\\-_#%?^`&=~}{|]+)*@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([\\w-['&_\\]]]+)(\\.[\\w-['&_\\]]]+)*))(\\]?)$

我正在使用 XRegExp。我在这里错过了什么吗?是否有将普通正则表达式转换为 JavaScript 的转换器之类的东西:)?

这是我的功能:

 function CheckEmailAddress(email) {
     var reg = new XRegExp("^[a-zA-Z0-9!$'*+/\\-_#%?^`&=~}{|]+(\\.[a-zA-Z0-9!$'*+/\\-_#%?^`&=~}{|]+)*@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([\\w-['&_\\]]]+)(\\.[\\w-['&_\\]]]+)*))(\\]?)$")

     if (reg.test(email) == false) {
         return false;
     }

     return true;
 }

对于简单的“abc@123.com”电子邮件地址,它返回 false。

提前致谢!

凯文

4

1 回答 1

2

问题是您的正则表达式包含字符类减法。JavaScriptRegExp不支持它们,XRegExp. (我最初记错并评论说它确实如此,但事实并非如此。)

但是,字符类减法可以替换为负前瞻,因此:

[\w-['&_\\]]]

可以变成这样:

(?:(?!['&_\\]])\\w)

Both mean "any word character but not one in the set '&_]". The expression \w does not match ', & or ] so we can simplify to:

(?:(?!_)\\w)

Or since \w is [A-Za-z0-9_], we can just remove the underscore from the list and further simplify to:

[A-Za-z0-9]

So the final RegExp is this:

new RegExp("^[a-zA-Z0-9!$'*+/\\-_#%?^`&=~}{|]+(\\.[a-zA-Z0-9!$'*+/\\-_#%?^`&=~}{|]+)*@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([A-Za-z0-9]+)(\\.[A-Za-z0-9]+)*))(\\]?)$")

I've done modest testing with this RegExp, but you should do due diligence on checking it.

It is not strictly necessary to go through the negative lookahead step to simplify the regular expression but knowing that character class subtractions can be replaced with negative lookaheads is useful in more general cases where manual simplification would be difficult or brittle.

于 2014-02-01T13:12:03.530 回答