【问题标题】:Ruby 1.9 unicode escapes in Regexp正则表达式中的 Ruby 1.9 unicode 转义
【发布时间】:2013-06-04 08:05:40
【问题描述】:

我刚刚将一个旧项目升级到 Ruby 1.9.3。我在使用 unicode 字符串时遇到了很多麻烦。归结为:

p = "\\username"; "Any String".match(/#{p}/)

这适用于 1.8,并按预期返回 nil。但是,在 1.9 中它会抛出:

ArgumentError: invalid Unicode escape

我正在尝试匹配字符串中的'\u'。我认为这两个反斜杠会使其免于注册为 unicode。

我在这里错过了什么?

编辑:单引号也不起作用:

1.9.3p429 :002 > p = '\\username'; "Any String".match(/#{p}/)
ArgumentError: invalid Unicode escape
from (irb):2

【问题讨论】:

    标签: ruby regex ruby-1.9 ruby-1.9.3


    【解决方案1】:

    当您执行/#{p}/ 时,这意味着p 将被解释为正则表达式。由于您的 p 现在等于 \username,因此此 Regexp 编译将失败(因为它是无效的 Unicode 转义序列):

    >> Regexp.new "\\username"
    RegexpError: invalid Unicode escape: /\username/
    

    即做/#{p}/等于写/\username/

    因此,您必须从任何正则表达式中转义 p,以便正确解释:

    "Any String".match(/#{Regexp.escape(p)}/)
    

    或者只是:

    "Any String".match(Regexp.escape(p))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-18
      • 2016-04-22
      • 2012-03-27
      • 1970-01-01
      相关资源
      最近更新 更多