我用这个

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

Regexp来验证电子邮件

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

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

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


当前回答

它采取了许多尝试,以创建一个电子邮件验证器,捕捉几乎所有的全球电子邮件需求。

扩展方法,你可以调用:

myEmailString.IsValidEmailAddress();

正则表达式模式字符串,你可以通过调用:

var myPattern = Regex.EmailPattern;

准则(主要是评论):

    /// <summary>
    /// Validates the string is an Email Address...
    /// </summary>
    /// <param name="emailAddress"></param>
    /// <returns>bool</returns>
    public static bool IsValidEmailAddress(this string emailAddress)
    {
        var valid = true;
        var isnotblank = false;

        var email = emailAddress.Trim();
        if (email.Length > 0)
        {
            // Email Address Cannot start with period.
            // Name portion must be at least one character
            // In the Name, valid characters are:  a-z 0-9 ! # _ % & ' " = ` { } ~ - + * ? ^ | / $
            // Cannot have period immediately before @ sign.
            // Cannot have two @ symbols
            // In the domain, valid characters are: a-z 0-9 - .
            // Domain cannot start with a period or dash
            // Domain name must be 2 characters.. not more than 256 characters
            // Domain cannot end with a period or dash.
            // Domain must contain a period
            isnotblank = true;
            valid = Regex.IsMatch(email, Regex.EmailPattern, RegexOptions.IgnoreCase) &&
                !email.StartsWith("-") &&
                !email.StartsWith(".") &&
                !email.EndsWith(".") && 
                !email.Contains("..") &&
                !email.Contains(".@") &&
                !email.Contains("@.");
        }

        return (valid && isnotblank);
    }

    /// <summary>
    /// Validates the string is an Email Address or a delimited string of email addresses...
    /// </summary>
    /// <param name="emailAddress"></param>
    /// <returns>bool</returns>
    public static bool IsValidEmailAddressDelimitedList(this string emailAddress, char delimiter = ';')
    {
        var valid = true;
        var isnotblank = false;

        string[] emails = emailAddress.Split(delimiter);

        foreach (string e in emails)
        {
            var email = e.Trim();
            if (email.Length > 0 && valid) // if valid == false, no reason to continue checking
            {
                isnotblank = true;
                if (!email.IsValidEmailAddress())
                {
                    valid = false;
                }
            }
        }
        return (valid && isnotblank);
    }

    public class Regex
    {
        /// <summary>
        /// Set of Unicode Characters currently supported in the application for email, etc.
        /// </summary>
        public static readonly string UnicodeCharacters = "À-ÿ\p{L}\p{M}ÀàÂâÆæÇçÈèÉéÊêËëÎîÏïÔôŒœÙùÛûÜü«»€₣äÄöÖüÜß"; // German and French

        /// <summary>
        /// Set of Symbol Characters currently supported in the application for email, etc.
        /// Needed if a client side validator is being used.
        /// Not needed if validation is done server side.
        /// The difference is due to subtle differences in Regex engines.
        /// </summary>
        public static readonly string SymbolCharacters = @"!#%&'""=`{}~\.\-\+\*\?\^\|\/\$";

        /// <summary>
        /// Regular Expression string pattern used to match an email address.
        /// The following characters will be supported anywhere in the email address:
        /// ÀàÂâÆæÇçÈèÉéÊêËëÎîÏïÔôŒœÙùÛûÜü«»€₣äÄöÖüÜß[a - z][A - Z][0 - 9] _
        /// The following symbols will be supported in the first part of the email address(before the @ symbol):
        /// !#%&'"=`{}~.-+*?^|\/$
        /// Emails cannot start or end with periods,dashes or @.
        /// Emails cannot have two @ symbols.
        /// Emails must have an @ symbol followed later by a period.
        /// Emails cannot have a period before or after the @ symbol.
        /// </summary>
        public static readonly string EmailPattern = String.Format(
            @"^([\w{0}{2}])+@{1}[\w{0}]+([-.][\w{0}]+)*\.[\w{0}]+([-.][\w{0}]+)*$",                     //  @"^[{0}\w]+([-+.'][{0}\w]+)*@[{0}\w]+([-.][{0}\w]+)*\.[{0}\w]+([-.][{0}\w]+)*$",
            UnicodeCharacters,
            "{1}",
            SymbolCharacters
        );
    }

其他回答

string patternEmail = @"(?<email>\w+@\w+\.[a-z]{0,3})";
Regex regexEmail = new Regex(patternEmail);

像。museum这样的顶级域名就不是这样匹配的,还有一些其他的长顶级域名。此外,你可以使用MailAddress类验证电子邮件地址,微软在这里解释了一个说明:

与使用正则表达式验证电子邮件地址不同, 你可以使用System.Net.Mail.MailAddress类。来确定 电子邮件地址是否有效,将电子邮件地址传递给 mailaddress (String)类构造函数。

public bool IsValid(string emailaddress)
{
    try
    {
        MailAddress m = new MailAddress(emailaddress);

        return true;
    }
    catch (FormatException)
    {
        return false;
    }
}

这为您省去了很多麻烦,因为您不必编写(或试图理解他人的)正则表达式。

编辑:对于那些对尝试/捕捉过敏的人:在。net 5中,你可以使用MailAddress.TryCreate。请参见https://stackoverflow.com/a/68198658,包括如何修复的示例。,空格,缺失。tld等。

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,}))$

目前对我来说,最好的方法是使用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");
   }
}

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

为什么不使用基于EF6属性的电子邮件验证?

正如您在上面所看到的,电子邮件的Regex验证总是有一些漏洞。如果您使用的是EF6数据注释,则可以通过EmailAddress数据注释属性轻松实现可靠且更强的电子邮件验证。当我在电子邮件输入字段上获得移动设备特定的正则表达式失败时,我不得不删除以前用于电子邮件的正则表达式验证。当数据注释属性用于电子邮件验证时,移动设备上的问题就解决了。

public class LoginViewModel
{
    [EmailAddress(ErrorMessage = "The email format is not valid")]
    public string Email{ get; set; }