Ruby匹配错误的特殊字符,如“|”

时间:2016-01-12 13:34:30

标签: arrays ruby regex match

代码:

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 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"]

1 个答案:

答案 0 :(得分:2)

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

this is | a test

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

您可以使用Regex.escape

/#{Regex.escape(c)}/