简体   繁体   English

正则表达式 Email 验证

[英]Regex Email validation

I use this我用这个

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

regexp to validate the email用于验证 email 的正则表达式

([\w\.\-]+) - this is for the first-level domain (many letters and numbers, also point and hyphen) ([\w\.\-]+) - 这是用于一级域(许多字母和数字,还有点和连字符)

([\w\-]+) - this is for second-level domain ([\w\-]+) - 这是二级域名

((\.(\w){2,3})+) - and this is for other level domains(from 3 to infinity) which includes a point and 2 or 3 literals ((\.(\w){2,3})+) - 这是针对其他级别的域(从 3 到无穷大),其中包括一个点和 2 或 3 个文字

what's wrong with this regex?这个正则表达式有什么问题?

EDIT:it doesn't match the "something@someth.ing" email编辑:它与“something@someth.ing”email 不匹配

TLD's like .museum aren't matched this way, and there are a few other long TLD's..museum这样的 TLD 不是这样匹配的,还有一些其他的长 TLD。 Also, you can validate email addresses using the MailAddress class as Microsoft explains here in a note:此外,您可以使用MailAddress 类验证电子邮件地址,正如 Microsoft在此处的注释中解释的那样:

Instead of using a regular expression to validate an email address, you can use the System.Net.Mail.MailAddress class.您可以使用 System.Net.Mail.MailAddress 类,而不是使用正则表达式来验证电子邮件地址。 To determine whether an email address is valid, pass the email address to the MailAddress.MailAddress(String) class constructor.要确定电子邮件地址是否有效,请将电子邮件地址传递给 MailAddress.MailAddress(String) 类构造函数。

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

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

This saves you a lot af headaches because you don't have to write (or try to understand someone else's) regex.这为您节省了很多麻烦,因为您不必编写(或尝试理解其他人的)正则表达式。

EDIT : For those who are allergic to try/catch : In .NET 5 you can use MailAddress.TryCreate .编辑:对于那些对try/catch过敏的人:在 .NET 5 中,您可以使用MailAddress.TryCreate See also https://stackoverflow.com/a/68198658 , including an example how to fix .., spaces, missing .TLD, etc.另请参阅https://stackoverflow.com/a/68198658 ,包括如何修复 ..、空格、缺少 .TLD 等的示例。

I think @"^([\\w\\.\\-]+)@([\\w\\-]+)((\\.(\\w){2,3})+)$" should work.我认为@"^([\\w\\.\\-]+)@([\\w\\-]+)((\\.(\\w){2,3})+)$"应该有效。
You need to write it like你需要这样写

string email = txtemail.Text;
Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
Match match = regex.Match(email);
if (match.Success)
    Response.Write(email + " is correct");
else
    Response.Write(email + " is incorrect");

Be warned that this will fail if:请注意,如果出现以下情况,这将失败:

  1. There is a subdomain after the @ symbol. @符号后有一个子域。

  2. You use a TLD with a length greater than 3, such as .info您使用长度大于 3 的 TLD,例如.info

I have an expression for checking email addresses that I use.我有一个用于检查我使用的电子邮件地址的表达式。

Since none of the above were as short or as accurate as mine, I thought I would post it here.由于以上没有一个像我的一样简短或准确,我想我会把它贴在这里。

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

For more info go read about it here: C# – Email Regular Expression有关更多信息,请在此处阅读: C# – 电子邮件正则表达式

Also, this checks for RFC validity based on email syntax, not for whether the email really exists.此外,这会根据电子邮件语法检查 RFC 有效性,而不是检查电子邮件是否真的存在。 The only way to test that an email really exists is to send and email and have the user verify they received the email by clicking a link or entering a token.测试电子邮件是否真的存在的唯一方法是发送和发送电子邮件,并让用户通过单击链接或输入令牌来验证他们收到了电子邮件。

Then there are throw-away domains, such as Mailinator.com, and such.然后是一次性域名,例如 Mailinator.com 等。 This doesn't do anything to verify whether an email is from a throwaway domain or not.这对验证电子邮件是否来自一次性域没有任何作用。

I found nice document on MSDN for it.我在 MSDN 上找到了不错的文档。

How to: Verify that Strings Are in Valid Email Format http://msdn.microsoft.com/en-us/library/01escwtf.aspx (check out that this code also supports the use of non-ASCII characters for Internet domain names.)如何:验证字符串是否采用有效的电子邮件格式http://msdn.microsoft.com/en-us/library/01escwtf.aspx (查看此代码是否还支持对 Internet 域名使用非 ASCII 字符。 )

There are 2 implementation, for .Net 2.0/3.0 and for .Net 3.5 and higher.有 2 个实现,分别用于 .Net 2.0/3.0 和 .Net 3.5 及更高版本。
the 2.0/3.0 version is: 2.0/3.0 版本是:

bool IsValidEmail(string strIn)
{
    // Return true if strIn is in valid e-mail format.
    return Regex.IsMatch(strIn, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"); 
}

My tests over this method give:我对这种方法的测试给出:

Invalid: @majjf.com
Invalid: A@b@c@example.com
Invalid: Abc.example.com
Valid: j..s@proseware.com
Valid: j.@server1.proseware.com
Invalid: js*@proseware.com
Invalid: js@proseware..com
Valid: ma...ma@jjf.co
Valid: ma.@jjf.com
Invalid: ma@@jjf.com
Invalid: ma@jjf.
Invalid: ma@jjf..com
Invalid: ma@jjf.c
Invalid: ma_@jjf
Invalid: ma_@jjf.
Valid: ma_@jjf.com
Invalid: -------
Valid: 12@hostname.com
Valid: d.j@server1.proseware.com
Valid: david.jones@proseware.com
Valid: j.s@server1.proseware.com
Invalid: j@proseware.com9
Valid: j_9@[129.126.118.1]
Valid: jones@ms1.proseware.com
Invalid: js#internal@proseware.com
Invalid: js@proseware.com9
Invalid: js@proseware.com9
Valid: m.a@hostname.co
Valid: m_a1a@hostname.com
Valid: ma.h.saraf.onemore@hostname.com.edu
Valid: ma@hostname.com
Invalid: ma@hostname.comcom
Invalid: MA@hostname.coMCom
Valid: ma12@hostname.com
Valid: ma-a.aa@hostname.com.edu
Valid: ma-a@hostname.com
Valid: ma-a@hostname.com.edu
Valid: ma-a@1hostname.com
Valid: ma.a@1hostname.com
Valid: ma@1hostname.com

The following code is based on Microsoft's Data annotations implementation on github and I think it's the most complete validation for emails:以下代码基于微软在github的数据注释实现,我认为这是对电子邮件最完整的验证:

public static Regex EmailValidation()
{
    const string pattern = @"^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$";
    const RegexOptions options = RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture;

    // Set explicit regex match timeout, sufficient enough for email parsing
    // Unless the global REGEX_DEFAULT_MATCH_TIMEOUT is already set
    TimeSpan matchTimeout = TimeSpan.FromSeconds(2);

    try
    {
        if (AppDomain.CurrentDomain.GetData("REGEX_DEFAULT_MATCH_TIMEOUT") == null)
        {
            return new Regex(pattern, options, matchTimeout);
        }
    }
    catch
    {
        // Fallback on error
    }

    // Legacy fallback (without explicit match timeout)
    return new Regex(pattern, options);
}

This does not meet all of the requirements of RFCs 5321 and 5322, but it works with the following definitions.这并不满足 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})$";

Below is the code下面是代码

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

Best email validation 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])?

And it's usage :-它的用法是:-

bool isEmail = Regex.IsMatch(emailString, @"\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", RegexOptions.IgnoreCase);

Why not use EF6 attribute based e-mail validation?为什么不使用基于 EF6 属性的电子邮件验证?

As you can see above, Regex validation for e-mail always has some hole in it.正如您在上面看到的,电子邮件的正则表达式验证总是有一些漏洞。 If you are using EF6 data annotations, you can easily achieve reliable and stronger e-mail validation with EmailAddress data annotation attribute available for that.如果您正在使用 EF6 数据注释,则可以使用可用的EmailAddress数据注释属性轻松实现可靠且更强大的电子邮件验证。 I had to remove the regex validation I used before for e-mail when I got mobile device specific regex failure on e-mail input field.当我在电子邮件输入字段上遇到移动设备特定的正则表达式失败时,我不得不删除我之前用于电子邮件的正则表达式验证。 When the data annotation attribute used for e-mail validation, the issue on mobile was resolved.当数据注释属性用于电子邮件验证时,解决了移动设备上的问题。

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

Try this on for size:试试这个尺寸:

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

This regex works perfectly:这个正则表达式完美地工作:

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");
}
new System.ComponentModel.DataAnnotations.EmailAddressAttribute().IsValid(input)

Try this, it's working for me:试试这个,它对我有用:

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(".");
    }
}

As an update to the popular answer of Alex : In .NET 5 MailAddress now has a TryCreate.作为对Alex的热门回答的更新:在 .NET 5 MailAddress 现在有一个 TryCreate。 So you can do something like:因此,您可以执行以下操作:

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

This one prevents invalid emails mentioned by others in the comments:这可以防止其他人在评论中提到的无效电子邮件:

Abc.@example.com
Abc..123@example.com
name@hotmail
toms.email.@gmail.com
test@-online.com

It also prevents emails with double dots:它还可以防止带有双点的电子邮件:

hello..world@example..com

Try testing it with as many invalid email addresses as you can find.尝试使用尽可能多的无效电子邮件地址对其进行测试。

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}$).*");
}

See validate email address using regular expression in C# .请参阅在 C# 中使用正则表达式验证电子邮件地址

It has taken many attempts to create an email validator which catches nearly all worldwide requirements for email.已经进行了多次尝试来创建一个电子邮件验证器,它几乎可以满足全球对电子邮件的所有要求。

Extension method you can call with:您可以调用的扩展方法:

myEmailString.IsValidEmailAddress();

Regex pattern string you can get by calling:您可以通过调用获取正则表达式模式字符串:

var myPattern = Regex.EmailPattern;

The Code (mostly comments):代码(主要是评论):

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

To validate your email ID, you can simply create such method and use it.要验证您的电子邮件 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);
    }

This will return True / False.这将返回真/假。 (Valid / Invalid Email Id) (有效/无效的电子邮件 ID)

Email validation using regex使用正则表达式验证电子邮件

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

Source: email validation c#来源: 电子邮件验证 c#

Validation Without Regex using MailAddress.MailAddress(String) class constructor使用MailAddress.MailAddress(String)类构造函数在没有正则表达式的情况下进行验证

public bool IsEmailValid(string emailaddress)
{
 try
 {
    MailAddress m = new MailAddress(emailaddress);
    return true;
 }
 catch (FormatException)
 {
    return false;
 }
}
public static bool ValidateEmail(string str)
{                       
     return Regex.IsMatch(str, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
}

I use the above code to validate the email address.我使用上面的代码来验证电子邮件地址。

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

This is my favorite approach to this so far:到目前为止,这是我最喜欢的方法:

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

Then use the created string extension like:然后使用创建的字符串扩展,如:

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

There's no perfect regular expression, but this one is pretty strong, I think, based on study of RFC5322 .没有完美的正则表达式,但我认为,基于对RFC5322 的研究,这个正则表达式非常强大。 And with C# string interpolation, pretty easy to follow, I think, as well.使用 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);

Vetted with NUnit 2.x .通过NUnit 2.x审查。

Just let me know IF it doesn't work :)如果它不起作用,请告诉我:)

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;

}

I've created a FormValidationUtils class to validate email:我创建了一个 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);
    }
}

here is our Regex for this case:这是我们针对这种情况的正则表达式:

@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                       @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                       @".)+))([a-zA-Z]{2,6}|[0-9]{1,3})(\]?)$",

there are three parts, which are checcked.一共分为三部分,经过检查。 the last one is propably the one you need.最后一个可能是你需要的。 the specific term {2,6} indicates you the min/max length of the TLD at the end.特定术语{2,6}表示最后 TLD 的最小/最大长度。 HTH HTH

Try the Following Code:尝试以下代码:

using System.Text.RegularExpressions;
if  (!Regex.IsMatch(txtEmail.Text, @"^[a-z,A-Z]{1,10}((-|.)\w+)*@\w+.\w{3}$"))
        MessageBox.Show("Not valid email.");

STRING SEARCH USING REGEX METHOD IN C#在 C# 中使用正则表达式方法进行字符串搜索

How to validate an Email by Regular Expression?如何通过正则表达式验证电子邮件?

string EmailPattern = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
if (Regex.IsMatch(Email, EmailPattern, RegexOptions.IgnoreCase))
{
    Console.WriteLine("Email: {0} is valid.", Email);
}
else
{
    Console.WriteLine("Email: {0} is not valid.", Email);
}

Use Reference String.Regex() Method使用参考String.Regex() 方法

1 1

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

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

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

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

^(?:[\\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])\\]))$

I've been using the Regex.IsMatch().我一直在使用 Regex.IsMatch()。

First of all you need to add the next statement:首先,您需要添加下一条语句:

using System.Text.RegularExpressions;

Then the method looks like:然后该方法看起来像:

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

It's a private method because of my logic but you can put the method as static in another Layer such as "Utilities" and call it from where you need.由于我的逻辑,这是一个私有方法,但您可以将该方法作为静态方法放在另一个层(例如“实用程序”)中,并从您需要的地方调用它。

I use:我用:

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

Here is my solution after gathering info from here and Microsoft documents:从此处和 Microsoft 文档收集信息后,这是我的解决方案:

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

At the moment for me the best approach is to use the FluentValidation library.目前对我来说最好的方法是使用FluentValidation库。 It has a built-in validator for the email address.它有一个针对 email 地址的内置验证器。 Usage is very simple and you don't have to think about regex.使用非常简单,您不必考虑正则表达式。

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

I realize the question was asked a long time ago, but maybe refreshing the answer with a newer approach will help someone.我意识到很久以前就有人问过这个问题,但也许用更新的方法刷新答案会对某人有所帮助。

Visual studio had this for years. Visual Studio已经有多年了。

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

Hope this helps! 希望这可以帮助!

This code will help to validate email id using regex expression in c#.Net..it is easy to use 此代码将有助于使用c#.Net中的正则表达式来验证电子邮件ID。易于使用

if (!System.Text.RegularExpressions.Regex.IsMatch("<Email String Here>", @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"))
        {
            MessageBox.show("Incorrect Email Id.");
        }

A combination of the above responses.上述响应的组合。 I would use the Microsoft preferred approach of using MailAddress but implement as an extension of string:我会使用 Microsoft 首选的使用 MailAddress 的方法,但作为字符串的扩展来实现:

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

Then just validate any string as an email address with:然后只需将任何字符串验证为 email 地址:

string customerEmailAddress = "bert@potato.com";
customerEmailAddress.IsValidEmailAddress()

Clean simple and portable.清洁简单且便携。 Hope it helps someone.希望它能帮助别人。 Regex for emails are messy.电子邮件的正则表达式很乱。

That said MattSwanson has a blog on this very topic and he strongly suggests NOT using regexs and instead just check for '@' abd maybe a dot.也就是说,MattSwanson 有一个关于这个主题的博客,他强烈建议不要使用正则表达式,而只是检查“@”abd 可能是一个点。 Read his explanation here: https://mdswanson.com/blog/2013/10/14/how-not-to-validate-email-addresses.html在这里阅读他的解释: https://mdswanson.com/blog/2013/10/14/how-not-to-validate-email-addresses.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM