C#正则表达式验证电子邮件 [英] c# regex email validation

查看:141
本文介绍了C#正则表达式验证电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用这个

  @^([\\ W \\ \\  - ] +)@([\\ W \\  - ] +)。((\\(\\ W){2,3}) +)$

正则表达式验证电子邮件

([\\ W \\ \\ - ] +) - 这是第一级域(很多字母和数字,还点和连字符)结果结果
([\\ W \\ - ] +) - 这是二级域名搜索结果
((\\(\\ W){2,3})+。) - 这是其他顶级域名(3至无穷大),它包括一个点,或2 3文本搜索

有什么不对的正则表达式?

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


解决方案

TLD的如 .museum 不匹配这样一来,还有一些其他的长期TLD的。另外,还可以使用 MailAddress类作为微软解释验证电子邮件地址这里在一份报告:


  

而不是使用常规的前pression来验证电子邮件地址,
  您可以使用System.Net.Mail.MailAddress类。为了确定
  电子邮件地址是否有效,通过电子邮件地址的
  MailAddress.MailAddress(字符串)类的构造函数。


 公共BOOL的IsValid(字符串EMAILADDRESS)
{
    尝试
    {
        MailAddress M =新的MailAddress(EMAILADDRESS);        返回true;
    }
    赶上(FormatException)
    {
        返回false;
    }
}

这可以节省你很多AF头疼,因为你没有写(或试着去了解别人的)正则表达式。

I use this

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

regexp to validate the email

([\w\.\-]+) - this is for the first-level domain (many letters and numbers, also point and hyphen)

([\w\-]+) - this is for second-level domain

((\.(\w){2,3})+) - and this is for other level domains(from 3 to infinity) which includes a point and 2 or 3 literals

what's wrong with this regex?

EDIT:it doesn't match the "something@someth.ing" email

解决方案

TLD's like .museum aren't matched this way, and there are a few other long TLD's. Also, you can validate email addresses using the MailAddress class as Microsoft explains here in a note:

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

This saves you a lot af headaches because you don't have to write (or try to understand someone else's) regex.

这篇关于C#正则表达式验证电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆