我用这个

@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"

Regexp来验证电子邮件

([\w\.\-]+) -用于第一级域名(许多字母和数字,也有点和连字符) ([\w\-]+) -用于二级域 ((\.(\w){2,3})+) -这是用于其他级别域(从3到无穷),其中包括一个点和2或3个字面量

这个正则表达式有什么问题?

编辑:它与“something@someth.ing”电子邮件不匹配


当前回答

我想@”^ ((\ w \.\-]+)@([\ w \-]+)((\.(\ w){2,3}) +)美元“应该工作。 你需要这样写

string email = txtemail.Text;
Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
Match match = regex.Match(email);
if (match.Success)
    Response.Write(email + " is correct");
else
    Response.Write(email + " is incorrect");

请注意,如果出现以下情况,此操作将失败:

符号@后面有一个子域。 您使用的TLD长度大于3,例如.info

其他回答

Visual studio已经有很多年了。

\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

希望这能有所帮助!

这可以防止其他人在评论中提到的无效邮件:

Abc.@example.com
Abc..123@example.com
name@hotmail
toms.email.@gmail.com
test@-online.com

它还可以防止带有双点的电子邮件:

hello..world@example..com

试着用尽可能多的无效电子邮件地址进行测试。

using System.Text.RegularExpressions;

public static bool IsValidEmail(string email)
{
    return Regex.IsMatch(email, @"\A[a-z0-9]+([-._][a-z0-9]+)*@([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,4}\z")
        && Regex.IsMatch(email, @"^(?=.{1,64}@.{4,64}$)(?=.{6,100}$).*");
}

请参阅在c#中使用正则表达式验证电子邮件地址。

public static bool ValidateEmail(string str)
{                       
     return Regex.IsMatch(str, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
}

我使用上面的代码来验证电子邮件地址。

没有完美的正则表达式,但我认为,基于对RFC5322的研究,这个正则表达式相当强大。用c#字符串插值,我认为也很容易理解。

const string atext = @"a-zA-Z\d!#\$%&'\*\+-/=\?\^_`\{\|\}~";
var localPart = $"[{atext}]+(\\.[{atext}]+)*";
var domain = $"[{atext}]+(\\.[{atext}]+)*";
Assert.That(() => EmailRegex = new Regex($"^{localPart}@{domain}$", Compiled), 
Throws.Nothing);

用NUnit 2.x检查。

我创建了一个FormValidationUtils类来验证电子邮件:

public static class FormValidationUtils
{
    const string ValidEmailAddressPattern = "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$";

    public static bool IsEmailValid(string email)
    {
        var regex = new Regex(ValidEmailAddressPattern, RegexOptions.IgnoreCase);
        return regex.IsMatch(email);
    }
}