2014-03-12 197 views
0

我对电子邮件验证正则表达式规则如下焦炭类过早结束

的电子邮件地址的本地部分可以使用这些ASCII字符的:

Uppercase and lowercase English letters (a-z, A-Z) 
Digits 0 to 9 
Characters ! # $ % & ' * + -/= ?^_ ` { | } ~ 
Character . (dot, period, full stop) provided that it is not the first or last character, and provided also that it does not appear two or more times consecutively. 

/^(([^<>()[\]\\.,;:\[email protected]\"]+(\.[^<>()[\]\\.,;:\[email protected]\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/i 

这是在Javascript中工作,但在Ruby http://rubular.com/中,它给出错误“字符类的提前结束”。

我该如何解决这个问题?

回答

1

你应该逃脱打开符号范围内的方括号以及倒闭:

#   ⇓      ⇓ 
/^(([^<>()[\]\\.,;:\[email protected]\"]+(\.[^<>()[\]\\.,;:\[email protected]\"]+)*)…/ 

这应该是:

/^(([^<>()\[\]\\.,;:\[email protected]\"]+(\.[^<>()\[\]\\.,;:\[email protected]\"]+)*)…/ 

希望它能帮助。

+0

你怎么把这些小箭头在你的正则表达式的顶部? – aelor

+0

@aelor在[第3个键盘级别](http://en.wikipedia.org/wiki/AltGr_key)或/和[撰写密钥](http://en.wikipedia.org/wiki/Compose_Key)中。 – mudasobwa

1
irb(main):016:0> /[[e]/ 
SyntaxError: (irb):16: premature end of char-class: /[[e]/ 
     from /ms/dist/ruby/PROJ/core/2.0.0-p195/bin/irb:12:in `<main>' 

在JavaScript正则表达式引擎,你不需要逃避[文字组[]内。但是,您必须在Ruby正则表达式中使用\[

/^(([^<>()\[\]\\.,;:\[email protected]\"]+(\.[^<>()\[\]\\.,;:\[email protected]\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/i 
+0

非常感谢您的帮助! – Manish

2

括号是正则表达式语法的一部分。如果你想匹配一个文字括号(或任何其他特殊符号,就此而言),用一个反斜杠进行转义。

这应该工作:

/^(([^<>()\[\]\\.,;:\[email protected]\"]+(\.[^<>()\[\]\\.,;:\[email protected]\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/i