【问题标题】:Ruby matches wrong with special characters like "|"Ruby 与“|”等特殊字符匹配错误
【发布时间】:2016-04-17 03:42:36
【问题描述】:

代码:

arr = ["this is | a test","this is a second test","this must be a third test"]
res = ["this is | a test test test ","this is a second test test test","this must be a third test test test"]

result = Hash.new

arr.each do |c|
  res.each do |i|
    if (/#{c}/.match("#{i}" ))
      result["#{c}"] = i
    end
  end
end

puts result

结果:

["this is | a test" => "this is a second test test test",
 "this is a second test" => "this is a second test test test",
 "this must be a third test" => "this must be a third test test test"]

问题:

第一个匹配错误,“this is | a test”的最后一个匹配是“this is a second test”,我看到他先匹配第一个值,然后匹配第二个值。 插入中断不是一种选择。我怎样才能确定与“|”的匹配完全匹配,所以我可以得到以下结果:

["this is | a test" => "this is | a test test test ",
 "this is a second test" => "this is a second test test test",
 "this must be a third test" => "this must be a third test test test"]

【问题讨论】:

  • 无法复制。
  • 为什么不使用反斜杠?
  • @c650 因为数组是动态的,我们永远不知道“|”是否以及何时字符将出现。

标签: arrays ruby regex match


【解决方案1】:

问题在于,在正则表达式中,x|y 具有 “匹配正则表达式中的 xy 的特殊含义。因此,

this is | a test

确实会匹配"**this is **a second test test test"


你可以使用Regex.escape:

/#{Regex.escape(c)}/

【讨论】:

  • 感谢您的解决方案,就像一个魅力,解决方案:if (/#{Regexp.escape(c)}/.match("#{i}" ))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-25
  • 2014-07-12
  • 1970-01-01
相关资源
最近更新 更多