On Nov 29, 5:06 pm, James Moore <jamesthepi... / gmail.com> wrote: > On Nov 29, 2007 2:07 PM, <crm_... / mac.com> wrote: > > > For the following string: > > > 'cat sheep horse cat tac dog' > > > I would like to write a regular expression that matches any substring > > that is prefixed by the word 'cat', is then followed by any characters > > as long as those characters do not comprise the word 'cat', and then > > finally suffixed by the string 'dog'. Therefore, this expression > > should match the substring 'cat tac dog' in the above string. > > I think this gets you closer to where you want to be: > > irb(main):045:0> 'cat sheep horse cat tac dog' =~ /cat(?!.*cat)(.*)dog/ > => 16 > irb(main):046:0> $1 > => " tac " > irb(main):047:0> > > The (?! bit is a nonmatching lookahead. 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"