I was trying to write a regexp to replace all occurrences of
with
unless the
is already preceeded immediately by a
. I m doing this in Ruby 1.8.6 which doesn t support look behind in regexps so I tried:
# try to replace
proceeded by anything other than
with
str.gsub(/([^
])
/, "\1
") # \1 is the captured character to be kept
Given a string One
Two
Three
the intention was for
to be replaced with
and the existing
between Two and Three to be left unmodified. However only the first of the two
match. i.e. the result is:
"One
Two
Three"
I tried this in a couple of other regexp engines with the same result.
In the end I was able to solve this by using Oniguruma (which does support positive and negative look behind) instead of Ruby s built in regexps but I am still interested in why my alternative approach didn t work as I expected.
Thanks for any answers.