Reputation: 61
So I have this string
x = "{"1"=>"test","2"=>"Another=>Test","3"=>"Another=>One"}"
and I want to replace the rocket symbol that is beside a character to a pipe symbol. so the result is
x = "{"1"=>"test","2"=>"Another|Test","3"=>"Another|One"}"
I have this code right now
if x =~ /(=>\w)/).present?
x.match(/=>\w/) do |match|
#loop through matches and replace => with |
end
end
So basically my question is how do I loop through a matched by regex and replace the rocket sign to a pipe?
Upvotes: 0
Views: 112
Reputation: 164809
gsub
with a positive look-ahead will do it.
x = %q[{"1"=>"test","2"=>"Another=>Test","3"=>"Another=>One"}]
x.gsub!(%r{=>(?=\w)}, '|')
puts x
A look-ahead (or look-behind) matches, but does not include that bit in the match.
Though I think %r{=>(?=[^"])}
, a =>
which is not in front of a quote, is more correct.
x = %q[{"1"=>"what about => a space?","2"=>"Or=>(this)"}]
x.gsub!(%r{=>(?=[^"])}, '|')
puts x
Upvotes: 2