正则表达式电子邮件验证

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个回答

7
试试这个:

尝试以下内容:

public static bool IsValidEmailAddress(this string s)
{
    var 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])?");
    return regex.IsMatch(s);
}

6
这个正则表达式完美地起到了作用:
bool IsValidEmail(string email)
{
    return Regex.IsMatch(email, @"^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*@((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))\z");
}

test@test.istanbul 失败了。 - Soner from The Ottoman Empire
是的,它失败了,因为这个电子邮件地址也可以有效。现在你可以使用许多不同的域类型,例如在你的情况下是".istanbul"。我使用了这个解决方案。 - PeterPazmandi

5

尝试这个,对我来说有效:

public bool IsValidEmailAddress(string s)
{
    if (string.IsNullOrEmpty(s))
        return false;
    else
    {
        var regex = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
        return regex.IsMatch(s) && !s.EndsWith(".");
    }
}

5

这个代码可以防止评论中提到的无效电子邮件地址:

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#中的正则表达式验证电子邮件地址。 点击此处

这会针对我所有无效的电子邮件地址返回false。不幸的是,它也会针对许多有效的电子邮件地址返回false。 - Mark

5

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

    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)类构造函数进行无正则表达式验证

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

这不会匹配 me@localhost。请查看以下网站:TLD列表; 有效/无效地址; RFC822电子邮件地址的正则表达式 - Toto

4

为了验证您的电子邮件地址,您可以简单地创建这样的方法并使用它。

    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(有效/无效的电子邮件地址)。

2

创建一个可以满足全球几乎所有电子邮件要求的电子邮件验证器已经尝试了很多次。

您可以使用以下扩展方法进行调用:

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

1
这是迄今为止我最喜欢的方法:

public static class CommonExtensions
{
    public static bool IsValidEmail(this string thisEmail)
        => !string.IsNullOrWhiteSpace(thisEmail) &&
           new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$").IsMatch(thisEmail);
}

然后像这样使用创建的字符串扩展:

if (!emailAsString.IsValidEmail()) throw new Exception("Invalid Email");

1
   public bool VailidateEntriesForAccount()
    {
       if (!(txtMailId.Text.Trim() == string.Empty))
        {
            if (!IsEmail(txtMailId.Text))
            {
                Logger.Debug("Entered invalid Email ID's");
                MessageBox.Show("Please enter valid Email Id's" );
                txtMailId.Focus();
                return false;
            }
        }
     }
   private bool IsEmail(string strEmail)
    {
        Regex validateEmail = new Regex("^[\\W]*([\\w+\\-.%]+@[\\w\\-.]+\\.[A-Za-z] {2,4}[\\W]*,{1}[\\W]*)*([\\w+\\-.%]+@[\\w\\-.]+\\.[A-Za-z]{2,4})[\\W]*$");
        return validateEmail.IsMatch(strEmail);
    }

虽然这段代码可能回答了问题,但是提供关于为什么和/或如何回答问题的额外上下文可以提高其长期价值。 - AStopher

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

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


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