正则表达式电子邮件验证

269

我使用这个。

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

正则表达式用于验证电子邮件

([\w\.\-]+) - 这是一级域名(包括多个字母和数字、点号和连字符)

([\w\-]+) - 这是二级域名

((\.(\w){2,3})+) - 这是其他等级的域名(从3到无限)包括一个点和2或3个字符

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

编辑:它无法匹配"something@someth.ing"类型的电子邮件地址。


1
除了您未包含RFC [5321]和[5322]指定的有效字符之外,没有其他问题。 - Brad Christie
14
你有一个问题 -> 你想到了“正则表达式” -> 现在你有两个问题 ;-) - Jakub Konecki
foo+bar@example.com是什么意思? - Valerij
2
只是关于你的正则表达式的一个评论。随着这些新的.amsterdam,.info和其他域名,正则表达式应该是:@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,})+)$"" - Ton Snoei
显示剩余2条评论
37个回答

1

没有完美的正则表达式,但我认为这个非常强大,基于对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


1

如果不行,请告诉我IF :)

(保留html标记)
public static bool isValidEmail(this string email)
{

    string[] mail = email.Split(new string[] { "@" }, StringSplitOptions.None);

    if (mail.Length != 2)
        return false;

    //check part before ...@

    if (mail[0].Length < 1)
        return false;

    System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z0-9_\-\.]+$");
    if (!regex.IsMatch(mail[0]))
        return false;

    //check part after @...

    string[] domain = mail[1].Split(new string[] { "." }, StringSplitOptions.None);

    if (domain.Length < 2)
        return false;

    regex = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z0-9_\-]+$");

    foreach (string d in domain)
    {
        if (!regex.IsMatch(d))
            return false;
    }

    //get TLD
    if (domain[domain.Length - 1].Length < 2)
        return false;

    return true;

}

1

我创建了一个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);
    }
}

0

1

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

2

^(([^<>()[\]\\.,;:\s@\""]+(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$

0

我一直在使用Regex.IsMatch()。

首先,您需要添加下一个语句:

using System.Text.RegularExpressions;

那么这个方法看起来像:

private bool EmailValidation(string pEmail)
{
                 return Regex.IsMatch(pEmail,
                 @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
                 @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
                 RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
}

这是一个私有方法,因为我的逻辑需要,但你可以将该方法作为静态方法放在另一个层中,比如“工具类”,并从需要的地方调用它。


你还需要捕获超时错误。 - Reza Taba

0

正则表达式电子邮件模式:

^(?:[\\w\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\`\\{\\|\\}\\~]+\\.)*[\\w\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\`\\{\\|\\}\\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\\-](?!\\.)){0,61}[a-zA-Z0-9]?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\\[(?:(?:[01]?\\d{1,2}|2[0-4]\\d|25[0-5])\\.){3}(?:[01]?\\d{1,2}|2[0-4]\\d|25[0-5])\\]))$

0

我使用:

public bool ValidateEmail(string email)
{
   Regex regex = new Regex("^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$");
   if (regex.IsMatch(email))
      return true;

     return false;
}

0

目前对我来说最好的方法是使用FluentValidation库。它有一个内置的电子邮件地址验证器。使用非常简单,您不必考虑正则表达式。

using FluentValidation;
public class TestClass
{
   public string Email { get; set; }
}

public class TestClassValidator: AbstractValidator<TestClass>
{
   public TestClassValidator()
   {            
      RuleFor(x => x.Email).EmailAddress().WithMessage($"nameof{(TestClass.Email)} is not a valid email address");
   }
}

我知道这个问题很久以前就被问过了,但也许用一种更新的方法来回答会对某些人有所帮助。


0

在这里和微软文档中收集信息后,这是我的解决方案:

/// <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));
    }
}

0

我认为你的插入符号和美元符号是问题的一部分。你还应该稍微修改一下正则表达式,我使用了以下代码:@"[ :]+([\w.-]+)@([\w-.])+((.(\w){2,3})+)"


当您使用结果Trim(':')时 - ABMoharram

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接