Ruby正则表达式替换字符序列

时间:2019-03-07 17:22:58

标签: regex ruby

所以我有这个字符串

x = "{"1"=>"test","2"=>"Another=>Test","3"=>"Another=>One"}" 

,我想将字符旁边的火箭符号替换为管道符号。结果是

x = "{"1"=>"test","2"=>"Another|Test","3"=>"Another|One"}" 

我现在有此代码

if x =~ /(=>\w)/).present?
    x.match(/=>\w/) do |match|
      #loop through matches and replace => with |
    end
end

所以,基本上我的问题是我如何遍历正则表达式的匹配项并将火箭标志替换为管道?

1 个答案:

答案 0 :(得分:2)

gsubpositive look-ahead可以做到。

x = %q[{"1"=>"test","2"=>"Another=>Test","3"=>"Another=>One"}]
x.gsub!(%r{=>(?=\w)}, '|')
puts x

先行(或先行)匹配项,但不包含匹配项。

尽管我认为%r{=>(?=[^"])}(不在引号前面的=>)更正确。

x = %q[{"1"=>"what about => a space?","2"=>"Or=>(this)"}]
x.gsub!(%r{=>(?=[^"])}, '|')
puts x