【问题标题】:[[:punct:]] matches differently in irb and rails test [duplicate][[:punct:]] matches differently in irb and rails test [duplicate]
【发布时间】:2017-10-22 06:59:04
【问题描述】:

[[:punct:]] 在 Rails 模型测试调用时不匹配任何标点符号。使用以下代码

test "punctuation matched by [[:punct:]]" do
  punct_match = /\A[[:punct:]]+\Z/.match('[\]\[!"#$%&\'()*+,./:;<=>?@\^_`{|}~-]')

  puts punct_match
  puts punct_match.class
end

这会输出一个不可打印的字符和 NilClass。

但是,如果我执行相同的语句

punct_match = /\A[[:punct:]]+\Z/.match('[\]\[!"#$%&\'()*+,./:;<=>?@\^_`{|}~-]')

in irb 匹配正确并输出

[\]\[!"#$%&'()*+,./:;<=>?@\^_`{|}~-]
=> nil

我错过了什么?

Ruby 版本 => 2.2.4, Rails 版本 => 4.2.6

【问题讨论】:

  • 你在 irb 中究竟输入了什么?
  • 输入:punct_match = /\A[[:punct:]]+\Z/.match('[][!"#$%&\'()*+,./:; ?@\^_{|}~-]') output: #&lt;MatchData "[\\]\\[!\"\#$%&amp;'()*+,./:;&lt;=&gt;?@\\^_{|}~-]">
  • 使用 MRI v2.2.4?我试过这个,没有匹配。无法复制。
  • 啊,等一下。您使用的是 Ruby 2.4 而不是 2.2,不是吗?这个正则表达式的行为确实发生了变化。您的 rails vs pry 环境使用不同的 ruby​​ 版本。
  • 哇!铁轨不是宝石吗?它应该使用与您所知道的 ruby​​ 相同的 ruby​​。

标签: ruby regex unit-testing ruby-on-rails-4


【解决方案1】:

/[[:punct:]]/ 的行为在 ruby​​ 版本 2.4.0 中略有变化。

This bug 是在 ruby​​ 问题中提出的,它链接回 Onigmo 中的 this (much older) 问题 - 自 Ruby 2.0+ 以来使用的正则表达式引擎。

简短的回答是,这些字符在 ruby​​ 版本 &lt;2.4.0 中未被 /[[:punct:]]/ 匹配,现在已匹配:

$+<=>^`|~

您必须在比此 rails 应用程序更新的 ruby​​ 版本中运行 irb,这就是它匹配那里的原因。


另外,您应该将代码稍微修改为:

/\A[[:punct:]]+\z/.match('[]!"#$%&\'()*+,./:;<=>?@^_`{|}~-]')
  • 使用\z,而不是\Z。有一个slight difference\Z 也会匹配字符串末尾的新行。
  • 字符串中有不必要的反斜杠,例如'\^'
  • 您重复了[ 字符:'[\]\['

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-01
    • 1970-01-01
    • 2022-12-02
    • 2022-12-26
    • 2022-12-04
    • 2021-07-21
    • 2011-03-25
    • 2017-05-03
    相关资源
    最近更新 更多