我用这个

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

Regexp来验证电子邮件

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

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

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


当前回答

要验证您的电子邮件ID,您只需创建这样的方法并使用它。

    public static bool IsValidEmail(string email)
    {
        var r = new Regex(@"^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$");
        return !String.IsNullOrEmpty(email) && r.IsMatch(email);
    }

这将返回True / False。(有效/无效的电子邮件Id)

其他回答

以下是我从这里收集信息和微软文档后的解决方案:

/// <summary>
/// * TLD support from 2 to 5 chars (modify the values as you want)
/// * Supports: abc@gmail.com.us
/// * Non-sensitive case 
/// * Stops operation if takes longer than 250ms and throw a detailed exception
/// </summary>
/// <param name="email"></param>
/// <returns>valid: true | invalid: false </returns>
/// <exception cref="ArgumentException"></exception>

private bool validateEmailPattern(string email) {
    try {
        return Regex.IsMatch(email,
            @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,5})+)$",
            RegexOptions.None, TimeSpan.FromMilliseconds(250));
    } catch (RegexMatchTimeoutException) {
        // throw an exception explaining the task was failed 
        _ = email ?? throw new ArgumentException("email, Timeout/failed regexr processing.", nameof(email));
    }
}

这并不满足rfc 5321和5322的所有要求,但它适用于以下定义。

@"^([0-9a-zA-Z]([\+\-_\.][0-9a-zA-Z]+)*)+"@(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,17})$";

下面是代码

const String pattern =
   @"^([0-9a-zA-Z]" + //Start with a digit or alphabetical
   @"([\+\-_\.][0-9a-zA-Z]+)*" + // No continuous or ending +-_. chars in email
   @")+" +
   @"@(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,17})$";

var validEmails = new[] {
        "ma@hostname.com",
        "ma@hostname.comcom",
        "MA@hostname.coMCom",
        "m.a@hostname.co",
        "m_a1a@hostname.com",
        "ma-a@hostname.com",
        "ma-a@hostname.com.edu",
        "ma-a.aa@hostname.com.edu",
        "ma.h.saraf.onemore@hostname.com.edu",
        "ma12@hostname.com",
        "12@hostname.com",
};
var invalidEmails = new[] {
        "Abc.example.com",     // No `@`
        "A@b@c@example.com",   // multiple `@`
        "ma...ma@jjf.co",      // continuous multiple dots in name
        "ma@jjf.c",            // only 1 char in extension
        "ma@jjf..com",         // continuous multiple dots in domain
        "ma@@jjf.com",         // continuous multiple `@`
        "@majjf.com",          // nothing before `@`
        "ma.@jjf.com",         // nothing after `.`
        "ma_@jjf.com",         // nothing after `_`
        "ma_@jjf",             // no domain extension 
        "ma_@jjf.",            // nothing after `_` and .
        "ma@jjf.",             // nothing after `.`
    };

foreach (var str in validEmails)
{
    Console.WriteLine("{0} - {1} ", str, Regex.IsMatch(str, pattern));
}
foreach (var str in invalidEmails)
{
    Console.WriteLine("{0} - {1} ", str, Regex.IsMatch(str, pattern));
}

作为Alex的流行答案的更新:在。net 5中,MailAddress现在有一个TryCreate。所以你可以这样做:

public static bool IsValidEmail(string email)
{
    if (!MailAddress.TryCreate(email, out var mailAddress))
        return false;

    // And if you want to be more strict:
    var hostParts = mailAddress.Host.Split('.');
    if (hostParts.Length == 1)
        return false; // No dot.
    if (hostParts.Any(p => p == string.Empty))
        return false; // Double dot.
    if (hostParts[^1].Length < 2)
        return false; // TLD only one letter.

    if (mailAddress.User.Contains(' '))
        return false;
    if (mailAddress.User.Split('.').Any(p => p == string.Empty))
        return false; // Double dot or dot at end of user part.

    return true;
}
new System.ComponentModel.DataAnnotations.EmailAddressAttribute().IsValid(input)

我认为你的插入符号和美元符号是问题的一部分 你也应该修改一下正则表达式,我用的是下一个 @"[ :]+([\ w -] +) @ ((\ w -.])+((.(\ w){2,3}) +)”