我用这个

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

Regexp来验证电子邮件

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

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

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


当前回答

作为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;
}

其他回答

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

    string pattern = @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z";

    //check first string
   if (Regex.IsMatch(EmailId1 , pattern))
   {    
       //if email is valid
        Console.WriteLine(EmailId1+ " is a valid Email address ");
   }

来源:电子邮件验证c#

使用MailAddress.MailAddress(String)类构造函数没有Regex的验证

public bool IsEmailValid(string emailaddress)
{
 try
 {
    MailAddress m = new MailAddress(emailaddress);
    return true;
 }
 catch (FormatException)
 {
    return false;
 }
}

Visual studio已经有很多年了。

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

希望这能有所帮助!

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

扩展方法,你可以调用:

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
        );
    }
public static bool ValidateEmail(string str)
{                       
     return Regex.IsMatch(str, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
}

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

我使用:

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