简体   繁体   English

将长度验证合并到现有的电子邮件地址格式正则表达式中

[英]Incorporating length validation into an existing email address format regex

I am using this regex in C# for email format validation based on information from http://www.regular-expressions.info/email.html : 我正在根据来自http://www.regular-expressions.info/email.html的信息在C#中将此正则表达式用于电子邮件格式验证:

Regex.IsMatch("test@gmail.com", 
              @"^[A-Z0-9'._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}$",RegexOptions.IgnoreCase);

I would also like to validate that the total length of the email is between 5 - 254 characters. 我还想验证电子邮件的总长度在5到254个字符之间。 How should this regex be modified to satisfy the length condition? 应该如何修改此正则表达式以满足长度条件? I don't want to check the length of the string in C# explicitly. 我不想显式检查C#中字符串的长度。

I suggest you not put such restriction. 我建议你不要施加这样的限制。 if you really want the regex. 如果您真的想要正则表达式。 As paxdiablo said many number of questions exist in SO. 正如paxdiablo所说,SO中存在许多问题。 Email validation in regex 正则表达式中的电子邮件验证

^.{1,254}$

http://rick.measham.id.au/paste/explain.pl?regex=%5E.%7B1%2C150%7D%24 http://rick.measham.id.au/paste/explain.pl?regex=%5E.%7B1%2C150%7D%24

尽管单独进行长度检查可能更干净一些,但是您可以通过在表达式的开头添加不捕获的前瞻来合并长度约束:

^(?=.{5,254})[A-Z0-9'._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}$

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

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