.NET 中的正则表达式的问题在于不支持所有格量词。如果您删除它们,它会起作用。这是作为 C# 字符串的正则表达式:
@"^[-_a-z0-9\'+*$^&%=~!?{}]+(?:\.[-_a-z0-9\'+*$^&%=~!?{}]+)*@(?:(?![-.])[-a-z0-9.]+(?<![-.])\.[a-z]{2,6}|\d{1,3}(?:\.\d{1,3}){3})(?::\d+)?$"
这是一个基于 the page you linked to 的测试平台,包括所有应该匹配的字符串和前三个不应该匹配的字符串:
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);
}
}
}
输出:
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
False
False
False
一个问题是它无法匹配一些有效的电子邮件地址,例如foo\@bar@example.com。配得太多总比配得少好。