【问题标题】:Premature end of char-classchar 类过早结束
【发布时间】:2014-03-12 13:40:51
【问题描述】:

我有用于电子邮件验证以下规则的正则表达式

电子邮件地址的本地部分可以使用以下任何 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.

/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[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/ 中它给出错误“字符类过早结束”。

我该如何解决这个问题?

【问题讨论】:

    标签: ruby-on-rails ruby regex ruby-on-rails-3


    【解决方案1】:

    括号是正则表达式语法的一部分。如果您想匹配文字括号(或任何其他特殊符号),请使用反斜杠转义。

    这应该有效:

    /^(([^<>()\[\]\\.,;:\s@\"]+(\.[^<>()\[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[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
    

    【讨论】:

      【解决方案2】:

      您应该在符号范围内避开左方括号和右方括号:

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

      这应该是:

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

      希望对你有帮助。

      【讨论】:

      • 如何将这些小箭头放在正则表达式之上?
      • @aelor 在3rd keyboard level 或/和Compose Key 内。
      • @AlekseiMatiushkin 我应该只在这里逃脱一两次吗? data.gsub(/(?&lt;!\['"])test-match/m,", content_here) 或 data.gsub(/(?&lt;!\[\'"])test-match/m,", content_here)
      【解决方案3】:
      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 正则表达式中使用 \[。

      /^(([^<>()\[\]\\.,;:\s@\"]+(\.[^<>()\[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[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
      

      【讨论】:

      • 非常感谢它的帮助!
      猜你喜欢
      • 1970-01-01
      • 2017-09-28
      • 2014-07-26
      • 1970-01-01
      • 2012-09-08
      • 2015-01-08
      • 2011-08-19
      • 1970-01-01
      相关资源
      最近更新 更多