0
validate_email = ( email ) ->
   (/^([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22))*\x40([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d))*$/).test email

这可行,但它在 79 个字符时未能通过我的“最大行长度”测试,因此我一直在尝试使用 coffeescript.org 上的示例将其减少到少于 80 个字符(实际上最多 74 个):

RFC822 = /// ^ (
  ([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+
  | \x22([^\x0d\x22\x5c\x80-\xff]
  | \x5c[\x00-\x7f])*\x22)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a
  -\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+
  | \x22([^\x0d\x22\x5c\x80-\xff]
  | \x5c[\x00-\x7f])*\x22))*\x40([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a
  -\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+
  | \x5b([^\x0d\x5b-\x5d\x80-\xff]
  | \x5c[\x00-\x7f])*\x5d)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a
  -\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+
  | \x5b([^\x0d\x5b-\x5d\x80-\xff]
  | \x5c[\x00-\x7f])*\x5d))*$/
) ///
RFC822.test email

虽然这编译得很好,但它不起作用。它总是返回假。

我该怎么做呢?

4

2 回答 2

3

您可以从字符串构建(如果您转义反斜杠):

var re = new RegExp(
               "..." + 
               "..." + 
               "...");

JS中完整匹配器的要点,似乎工作正常,但我的CF生锈了,所以我不知道它是否转化为CF)

于 2013-04-12T10:51:46.280 回答
2

我该怎么做呢?

你不 - 正则表达式不适合解析电子邮件地址。

任何这样的正则表达式都注定要失败,因为现在存在的域名几乎打破了它们通常做出的所有假设,例如:

  • 长 ASCII TLD(如果 TLD 长于 4 个字符,我已经看到了 regexps which barf)
  • 不使用美国 ASCII 的国际域名 (IDN)

也就是说,使用交互式 Coffeescript 解释器,我只需调整几个字符就可以得到:

RFC822 = ///
^([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+
  | \x22([^\x0d\x22\x5c\x80-\xff]
  | \x5c[\x00-\x7f])*\x22)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a
  -\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+
  | \x22([^\x0d\x22\x5c\x80-\xff]
  | \x5c[\x00-\x7f])*\x22))*\x40([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a
  -\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+
  | \x5b([^\x0d\x5b-\x5d\x80-\xff]
  | \x5c[\x00-\x7f])*\x5d)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a
  -\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+
  | \x5b([^\x0d\x5b-\x5d\x80-\xff]
  | \x5c[\x00-\x7f])*\x5d))*$
///

这完全减少到原始的正则表达式。唯一的变化是删除了整个正则表达式周围的一对多余的大括号,以及/结束后的尾随$

于 2013-04-12T10:28:27.353 回答