Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regexp to match string1 unless preceded by string2

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...

like image 677
luca Avatar asked Jul 31 '09 16:07

luca


1 Answers

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.

like image 94
Jeremy Bourque Avatar answered Nov 16 '22 02:11

Jeremy Bourque