Perl Regex "Not" (negative lookahead)

Go To StackoverFlow.com

21

I'm not terribly certain what the correct wording for this type of regex would be, but basically what I'm trying to do is match any string that starts with "/" but is not followed by "bob/", as an example.

So these would match:

/tom/
/tim/
/steve

But these would not

tom
tim
/bob/

I'm sure the answer is terribly simple, but I had a difficult time searching for "regex not" anywhere. I'm sure there is a fancier word for what I want that would pull good results, but I'm not sure what it would be.

Edit: I've changed the title to indicate the correct name for what I was looking for

2012-04-04 00:12
by GoldenNewby
what about /jimbob/? what about /bob/apples - ysth 2012-04-04 02:58
For my purposes /jimbob/ was okay, but /bob/apples was no - GoldenNewby 2012-04-04 22:58


21

You can use a negative lookahead (documented under "Extended Patterns" in perlre):

/^\/(?!bob\/)/
2012-04-04 00:23
by anonymous coward
Probably /^\/(?!bob\/)/ , though-- but you got the gist of it. Thanks - GoldenNewby 2012-04-04 00:25
@GoldenNewby Woops, overlooked that part of the questio - anonymous coward 2012-04-04 00:25
With default regex flags now a feature, that ^ is better written as \A. With alternate delimiters and /x, it looks like m| \A / (?!bob/) |x - brian d foy 2012-04-04 03:41
@brian d foy, It's preposterous to suggest the existence this feature means /^/ has to be changed to /\A/, /$/ to /(?=\n?\z)/, /./ to /[^\n]/ and / / to /[ ]/ - ikegami 2012-04-04 07:45
@ikegami: $ should be \z more often than not anyway; I am not without appreciation for a reason to use the parallel \Aysth 2012-04-05 05:05
Or, much more readable: m{^/(?!bob/)}mscha 2012-04-17 17:18
Ads