关于邮件地址的regular expression 问题

一个邮件系统需要下面的规则:
Username:
Begin with (a-zA-Z0-9_/-/.’)
Contain (a-zA-Z0-9_/-/.’)
Can’t have two adjacent periods

Domain:
Begin and end with (a-zA-Z0-9)
Contain (a-zA-Z0-9_/-/.)
Can’t have two adjacent periods

我写的规则如下:
internal static readonly Regex regEmail = new Regex(@"^(/.|(/.?[a-zA-Z0-9_'/-]+/.?)+)@[a-zA-Z0-9]([a-zA-Z0-9_/-]*/.?[a-zA-Z0-9_/-]+)*/.([a-zA-Z0-9_/-]+/.?[a-zA-Z0-9_/-]*)*[a-zA-Z0-9]$" , RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.CultureInvariant);

这个规则显得很复杂,从中抽取出了一个规则"Can’t have two adjacent periods",而用小段程序来实现IndexOf("..")。因此规则就可以写成:internal static readonly Regex regEmail = new Regex(
            @"^[a-zA-Z0-9_'/-/.]+@[a-zA-Z0-9][a-zA-Z0-9_/-/.]*/.[a-zA-Z0-9_/-/.]*[a-zA-Z0-9]$",
            RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.CultureInvariant);
if (email.IndexOf("..") > -1)
// 非法

我没有用/w代替[a-zA-Z0-9_],是因为我没有选择RegexOptions.ECMAScript。另外,在MSDN中对RegexOptions.ECMAScript的描述如下:
“指定已为表达式启用了符合 ECMAScript 的行为。此选项仅可与 IgnoreCase 和 Multiline 标志一起使用。将 ECMAScript 同任何其他标志一起使用将导致异常。”
但是它可以与以下options连用,但并没有导致异常:
RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.ECMAScript

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值