一个邮件系统需要下面的规则:
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