yermej wrote: > > Nonmatching (or negative) lookahead is what you want, and with some > adjustment of the capture you get: > > 'cat sheep horse cat tac dog' =~ /(cat(?!.*cat).*dog)/ > => 16 > $1 > => "cat tac dog" Negative lookaheads that contain '.*' are hard to comprehend (at least for me). It is enough to add a 'cat' at the end and the regexp does not find any more the 'cat tac dog' that should be matched: 'cat sheep horse cat tac dog lion cat' =~ /(cat(?!.*cat).*dog)/ => nil Also notice that, when it works, it will always give the last expression present: 'cat sheep horse cat tac dog lion cat dog' =~ /(cat(?!.*cat).*dog)/ => 33 p $1 # => "cat dog" Daniel Sheppard wrote: > Working out negative regular expressions is normally best avoided. I would say that it is true when they contain '.*' type expressions; else they can be extremely useful. > Or if you want multiple matches: > > x = 'cat sheep horse cat tac dog cat cat sheep dog' > x.scan(/cat.*?dog/).map {|x| x.sub(/.*cat/,'cat')} > => ["cat tac dog", "cat sheep dog"] Very ingenious... Raul -- Posted via http://www.ruby-forum.com/.