简体   繁体   English

用于电子邮件地址验证的正则表达式

[英]Regex for Email Address validation

I am trying to validate email addresses. 我正在尝试验证电子邮件地址。 Currently I'm using the following regex to validate email addresses which works perfectly fine. 目前,我正在使用以下正则表达式来验证可以正常工作的电子邮件地址。 But I now want to tweek it and allow only min 2 and max 40 characters for the domain-part of the email address ie after the @ symbol. 但是,我现在想对它进行周处理,并在电子邮件地址的域部分(即@符号后)仅允许min 2个字符和max 40个字符。 I tried setting the range but I guess it wont work like this. 我尝试设置范围,但我想它不会像这样工作。 Where am I going wrong? 我要去哪里错了?

The Regex: 正则表达式:

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

Validating email addresses is non-trivial, and your regex as it is rejects perfectly good email addresses such as test+1234@localhost . 验证电子邮件地址并非易事,正则表达式正则表达式拒绝完美的电子邮件地址,例如test+1234@localhost If you need to do it yourself, have a look at RFC 822 §6 . 如果您需要自己做,请查看RFC 822§6

However, in C#, there is a class MailAddress with a constructor accepting a string argument. 但是,在C#中,有一个类MailAddress ,其构造函数接受字符串参数。 You can attempt to construct a MailAddress addr = new MailAddress(emailString) , and see whether it throws a FormatException . 您可以尝试构造一个MailAddress addr = new MailAddress(emailString) ,并查看它是否引发FormatException As a benefit, the MailAddress object has many useful methods for working with email addresses. 有益的是, MailAddress对象具有许多使用电子邮件地址的有用方法。

EDIT: My apologies, I missed that you were trying to limit the host length. 编辑:对不起,我想念您正在尝试限制主机长度。 If you create the MailAddress as above, then addr.Host will contain the hostname part, and you can check its length. 如果按上述方式创建MailAddress ,则addr.Host将包含主机名部分,您可以检查其长度。

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

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