正则expression式电子邮件validation

我用这个

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

正则expression式来validation电子邮件

([\w\.\-]+) – 这是为一级域(许多字母和数字,也是点和连字符)

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

((\.(\w){2,3})+) – 这是为其他水平的领域(从3到无穷),其中包括一个点和2或3文字

这个正则expression式有什么问题?

编辑:它不符合“something@someth.ing”电子邮件

像.museum这样的顶级域名(TLD)不是这样匹配的,还有其他一些顶级域名(TLD)。 另外,您可以使用MailAddress类validation电子邮件地址,正如Microsoft 在此处所解释的:

而不是使用正则expression式来validation电子邮件地址,您可以使用System.Net.Mail.MailAddress类。 要确定电子邮件地址是否有效,请将电子邮件地址传递给MailAddress.MailAddress(String)类构造函数。

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

这可以节省很多头痛,因为你不必写(或试图理解别人的)正则expression式。

我认为@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"
你需要像写

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

被警告,这将失败,如果:

  1. @符号后面有一个子域。

  2. 您使用长度大于3的TLD,例如.info

我有一个expression式来检查我使用的电子邮件地址。

由于以上都不如我的简短或准确,所以我想我会在这里发表。

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

有关更多信息,请阅读此处: C#中的正则expression式(包括新的综合电子邮件模式)

我在MSDN上find了很好的文档。

如何validationstring是否处于有效的电子邮件格式http://msdn.microsoft.com/zh-cn/library/01escwtf.aspx (请检查此代码是否还支持使用非ASCII字符作为Internet域名。 )

对于.Net 2.0 / 3.0和.Net 3.5及更高版本,有2个实现。
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})(\]?)$"); } 

我对这个方法的testing给:

 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: dj@server1.proseware.com Valid: david.jones@proseware.com Valid: js@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: ma@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 

这并不符合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})$"; 

下面是代码

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

最好的电子邮件validation正则expression式

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

它的用法: –

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

这个防止他人在评论中提到的无效电子邮件:

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

它也可以防止双点电子邮件:

 hello..world@example..com 

尝试使用尽可能多的无效电子邮件地址进行testing。

 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]+)*\.)+[az]{2,4}\z") && Regex.IsMatch(email, @"^(?=.{1,64}@.{4,64}$)(?=.{6,100}$).*"); } 

请参阅在C#中使用正则expression式validation电子邮件地址 。

试试这个,它对我有用:

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

试试这个大小:

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

它已经采取了许多尝试创build一个电子邮件validation器,几乎可以满足全世界对电子邮件的要求。

您可以通过以下方式拨打电话:

 myEmailString.IsValidEmailAddress(); 

正则expression式模式string,你可以通过调用:

 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: az 0-9 ! # _ % & ' " = ` { } ~ - + * ? ^ | / $ // Cannot have period immediately before @ sign. // Cannot have two @ symbols // In the domain, valid characters are: az 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 ); } 

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

正如你上面看到的,电子邮件的正则expression式validation总是有一些漏洞。 如果您使用EF6数据注释,则可以使用EmailAddress数据注释属性轻松实现可靠且更强大的电子邮件validation。 当我在电子邮件input字段中遇到移动设备特定的正则expression式失败时,我必须删除之前用于电子邮件的正则expression式validation。 当用于电子邮件validation的数据注释属性解决了移动设备上的问题。

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

视觉工作室有这个多年。

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

希望这可以帮助!

  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+\.[az]{0,3})"; Regex regexEmail = new Regex(patternEmail); 

要validation您的电子邮件ID,您可以简单地创build此类方法并使用它。

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

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

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

试试以下代码:

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

使用REGEX方法在C#中进行STRINGsearch

如何通过正则expression式validation电子邮件?

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

使用引用String.Regex()方法

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

我认为你的脱字符和美元符号是问题的一部分你还应该修改一下正则expression式,我使用下一个@“[:] +([\ w .-] +)@([\ w – 。])+ (((\ w)的{2,3})+)”

正则expression式电子邮件模式:

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

以下代码基于github上的Microsoft数据注释实现 ,我认为这是对电子邮件最完整的validation:

 public static Regex EmailValidation() { const string pattern = @"^((([az]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([az]|\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)))@((([az]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([az]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([az]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([az]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([az]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([az]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([az]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([az]|[\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); } 

到目前为止,这是我最喜欢的方法:

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

然后使用创build的string扩展名如:

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

这段代码将有助于validation电子邮件ID使用正则expression式在C#.Net ..它很容易使用

 if (!System.Text.RegularExpressions.Regex.IsMatch("<Email String Here>", @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$")) { MessageBox.show("Incorrect Email Id."); } 
 public bool checkEmailAddress(string emailAddress) { // FullKade.COm string patternStrict = @"^(([^<>()[\]\\.,;:\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,}))$"; Regex reStrict = new Regex(patternStrict); bool isStrictMatch = reStrict.IsMatch(emailAddress); return isStrictMatch; // FullKade.COm } 

上述回应的组合。 我将使用Microsoft首选使用MailAddress的方法,但实现为string的扩展:

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

然后只是validation任何string作为电子邮件地址与:

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

干净简单和便携。 希望它可以帮助别人。 正则expression式的电子邮件是凌乱的。

这就是说MattSwanson在这个话题上有一个博客,他强烈build议不要使用正则expression式,而只是检查'@'abd也许是一个点。 请阅读他的解释: https : //mdswanson.com/blog/2013/10/14/how-not-to-validate-email-addresses.html