电子邮件验证:将用PHP(preg)编写的正则表达式转换为.NET(Regex)

dev*_*xer 4 .net php c# regex asp.net

基于此答案... 使用正则表达式验证电子邮件地址

这导致我到这个网站... http://fightingforalostcause.net/misc/2006/compare-email-regex.php

我想将此正则表达式用于我的ASP.NET MVC应用程序的电子邮件验证:

/^[-_a-z0-9\'+*$^&%=~!?{}]++(?:\.[-_a-z0-9\'+*$^&%=~!?{}]+)*+@(?:(?![-.])[-a-z0-9.]+(?<![-.])\.[a-z]{2,6}|\d{1,3}(?:\.\d{1,3}){3})(?::\d++)?$/iD
Run Code Online (Sandbox Code Playgroud)

不幸的是,我收到了这个错误

System.ArgumentException未被用户代码Message ="parsing \"/ ^ [-_ a-z0-9 \'+ $ ^&%=〜!?{}] ++(?:\.[-_ a-z0- 9 \'+ $ ^&%=〜!?{}] +)*+ @(?:(?![ - .])[ - a-z0-9.] +(?

有没有人曾经将它转换为可以被.NET的Regex类使用,或者是否有另一个.NET正则表达式类更适合PHP的preg_match功能?

Mar*_*ers 5

The problem with your regular expression in .NET is that the possessive quantifiers aren't supported. If you remove those, it works. Here's the regular expression as a C# string:

@"^[-_a-z0-9\'+*$^&%=~!?{}]+(?:\.[-_a-z0-9\'+*$^&%=~!?{}]+)*@(?:(?![-.])[-a-z0-9.]+(?<![-.])\.[a-z]{2,6}|\d{1,3}(?:\.\d{1,3}){3})(?::\d+)?$"
Run Code Online (Sandbox Code Playgroud)

Here's a test bed for it based on the page you linked to, including all the strings that should match and the first three of those that shouldn't:

using System;
using System.Text.RegularExpressions;

public class Program
{
    static void Main(string[] args)
    {
        foreach (string email in new string[]{
            "l3tt3rsAndNumb3rs@domain.com",
            "has-dash@domain.com",
            "hasApostrophe.o'leary@domain.org",
            "uncommonTLD@domain.museum",
            "uncommonTLD@domain.travel",
            "uncommonTLD@domain.mobi",
            "countryCodeTLD@domain.uk",
            "countryCodeTLD@domain.rw",
            "lettersInDomain@911.com",
            "underscore_inLocal@domain.net",
            "IPInsteadOfDomain@127.0.0.1",
            "IPAndPort@127.0.0.1:25",
            "subdomain@sub.domain.com",
            "local@dash-inDomain.com",
            "dot.inLocal@foo.com",
            "a@singleLetterLocal.org",
            "singleLetterDomain@x.org",
            "&*=?^+{}'~@validCharsInLocal.net",
            "missingDomain@.com",
            "@missingLocal.org",
            "missingatSign.net"
        })
        {
            string s = @"^[-_a-z0-9\'+*$^&%=~!?{}]+(?:\.[-_a-z0-9\'+*$^&%=~!?{}]+)*@(?:(?![-.])[-a-z0-9.]+(?<![-.])\.[a-z]{2,6}|\d{1,3}(?:\.\d{1,3}){3})(?::\d+)?$";
            bool isMatch = Regex.IsMatch(email, s, RegexOptions.IgnoreCase);
            Console.WriteLine(isMatch);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Output:

True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
False
False
False
Run Code Online (Sandbox Code Playgroud)

A problem though is that it fails to match some valid email-addresses, such as foo\@bar@example.com. It's better too match too much than too little.