tags:

views:

496

answers:

2

I want to use a regex to find a particular string in my sample, but I want the regex to fail if I first find another string. Let me give an example:

Match find_me only if we do not first encounter stop_here. (I don't care if stop_here occurs later in the sample.)

So, this should match:

blah blah find_me blah stop_here

But this shouldn't:

blah blah stop_here blah find_me

(I'm using the .NET regex engine)

+8  A: 
^(?:(?!stop_here).)*find_me
jitter
I knew I wanted a look-ahead, but I couldn't figure out how to use it. Thanks!
Jeremy Stein
+2  A: 

Not sure of the .NET regex engine, but I would just do a regexp search for find_me or stop_here and then check which one matched. In perl:

if ($stuff =~ /(find_me|stop_here)/) {
  if ($1 == "find_me") {
    ...
  } elsif ($1 == "stop_here") {
    ...
  }
}
Aaron
I didn't mention it in my question, but this is actually part of a larger regex, so I prefer the accepted answer, but yours is certainly easier to read. Thanks!
Jeremy Stein