c# - 正则表达式电子邮件验证

标签 c# regex validation

我用这个

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

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

([\w\.\-]+) - 这是用于一级域(许多字母和数字,还有点和连字符)

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

((\.(\w){2,3})+) - 这是针对其他级别的域(从 3 到无穷大),其中包括一个点和 2 或 3 个文字

这个正则表达式有什么问题?

编辑:它与“something@someth.ing”电子邮件不匹配

最佳答案

TLD 类似于 .museum不以这种方式匹配,还有其他一些长 TLD。此外,您可以使用 MailAddress class 验证电子邮件地址正如微软解释的那样 here在注释中:

Instead of using a regular expression to validate an email address, you can use the System.Net.Mail.MailAddress class. To determine whether an email address is valid, pass the email address to the MailAddress.MailAddress(String) class constructor.

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

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

这为您省去了很多麻烦,因为您不必编写(或尝试理解其他人的)正则表达式。

编辑:对于那些对 try/catch 过敏的人:在 .NET 5 中,您可以使用 MailAddress.TryCreate。另见 https://stackoverflow.com/a/68198658 ,包括如何修复 ..、空格、丢失的 .TLD 等的示例。

关于c# - 正则表达式电子邮件验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5342375/

相关文章:

c# - "tons"点的 Web 图表?

sql - Redshift 正则表达式匹配

python - 如何为 NLTK 中的歧义句子生成多个解析树?

javascript - 提交表单时,检查一个值,如果存在,则打开模式窗口以获取更多信息

silverlight - 验证摘要和 View 模型实现 INotifyDataErrorInfo 的问题

c# - 如何使用 UICollectionViewCompositionalLayout 和多种单元格类型创建自动调整大小的单元格?

c# - 如何在运行时使用反射从类对象获取属性值

c# - DryIoc 用函数解析

regex - {8} 字符串的 perl 正则表达式,包含十进制数字和字母,仅此而已

ajax - Zend_Form ajax 查询的 csrf 验证