deerchao的blog

Be and aware who you are.

强悍的电子邮件地址(email address)正则表达式

原始来源: RegexLib.com
修改后加入了两个新功能:
1,匹配类似 "lc <deerchao@xxx.com>" 这样的包含姓名的格式.
2,添加了四个命名组: name, email, user, domain. 这样可以方便取出相应的信息.

Regex re = new Regex(@"^((?'name'.+?)\s*<)?(?'email'(?>[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+\x20*|""(?'user'(?=[\x01-\x7f])[^""\\]|\\[\x01-\x7f])*""\x20*)*(?'angle'<))?(?'user'(?!\.)(?>\.?[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+)+|""((?=[\x01-\x7f])[^""\\]|\\[\x01-\x7f])*"")@(?'domain'((?!-)[a-zA-Z\d\-]+(?<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])[^\\\[\]]|\\[\x01-\x7f])+)\])(?'angle')(?(name)>)$", RegexOptions.Multiline | RegexOptions.ExplicitCapture);
MatchCollection mc 
= re.Matches(@"l c <abc@example.com>
Abc@example.com
aBC@example.com
abc.123@example.com
");
foreach (Match ma in mc)
{
  
}



原表达式的最大优点就是匹配能力强大,能吃下各种符合规范(RFC2882)的表达式.
匹配WikiPedia上的10/11个合法邮件地址格式,不合法的一个也不匹配:

Valid e-mail addresses

  • abc@example.com
  • Abc@example.com
  • aBC@example.com
  • abc.123@example.com
  • 1234567890@example.com
  • _______@example.com
  • abc+mailbox/department=shipping@example.com
  •  !#$%&'*+-/=?^_`.{|}~@example.com (all of these characters are allowed)
  • "abc@def"@example.com (anything goes inside quotation marks)
  • "Fred Bloggs"@example.com
  • "%()[]\;:,<>"@example.com

Invalid e-mail addresses

  • Abc.example.com (character @ is missing)
  • Abc.@example.com (character dot(.) is last in local part)
  • Abc..123@example.com (character dot(.) is double)
  • A@b@c@example.com (only one @ is allowed outside quotations marks)
  •  %()[]\;:,<>@example.com (none of the characters before the @ is allowed outside quotation marks)

posted on 2008-06-14 15:24 deerchao 阅读(247) 评论(0)  编辑 收藏


标题  
姓名  
主页
Email (博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
该文被作者在 2008-06-14 16:08 编辑过


相关链接:
 


<2008年6月>
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345

导航

统计

公告

给网络添加价值,就是让自己增加价值.

本博客所有内容,均为原创或对互联网已有资源的再加工,希望对你有用.在声明原作者的前提下,你可以任意使用,但本人对其正确性,使用的后果等不做任何担保,也不负任何责任.

正则表达式30分钟入门教程 v2.21 2007-8-3

I Want Spec#!

与我联系

搜索

 

常用链接

留言簿(64)

我管理的小组

我的标签

随笔档案(125)

文章分类(9)

文章档案(9)

新闻档案(9)

Links

积分与排名

最新评论

评论排行榜