regexp to match string1 unless preceded by string2

luca picture luca · Jul 31, 2009 · Viewed 9.8k times · Source

Using Ruby, how can I use a single regex to match all occurrences of 'y' in "xy y ay xy +y" that are NOT preceded by x (y, ay, +y)?
/[^x]y/ matches the preceding character too, so I need an alternative...

Answer

Jeremy Bourque picture Jeremy Bourque · Jul 31, 2009

You need a zero-width negative look-behind assertion. Try /(?<!x)y/ which says exactly what you're looking for, i.e. find all 'y' not preceeded by 'x', but doesn't include the prior character, which is the zero-width part.

Edited to add: Apparently this is only supported from Ruby 1.9 and up.