Given an example input like below:
s = "an example with 'one' word and 'two and three' words inside quotes"
I'm trying to iterate over parts outside of quotes to do some substitutions. For example to convert and to & but only outside of quotes to get:
an example with 'one' word & 'two and three' words inside quotes
If I were to change inside of quotes, I could simply do the following:
s.gsub(/'.*?'/){ |q| q.gsub(/and/, '&') }
to get:
an example with 'one' word and 'two & three' words inside quotes
I mainly tried two things to adapt this strategy to outside of quotes.
First, I tried to negate the regexp inside first gsub (i.e. /'.*?'/). I imagine if there were a suffix modifier like /v I could simply do s.gsub(/'.*?'/v){ ... }, unfortunately I couldn't find anything like this. There is a negative lookahead (i.e. (?!pat)) but I don't think it is what I need.
Second, I tried to use split with gsub! as such:
puts s.split(/'.*?'/){ |r| r.gsub!(/and/, '&') }
Using split I can iterate over the parts outside of quotes:
s.split(/'.*?'/){ |r| puts r }
to get:
an example with
word and
words inside quotes
However, I can't mutate these parts inside the block with gsub or gsub!. I guess I need a mutating version of split, something akin to gsub being a mutating version of scan, but there doesn't seem to be anything like this.
Is there an easy way to make either of these approaches work?