CrazySabbath
CrazySabbath

Reputation: 1334

Negative Lookahead Faults Regex

I have a regular expression:

^\/admin\/(?!(e06772ed-7575-4cd4-8cc6-e99bb49498c5)).*$

My input string:

/admin/e06772ed-7575-4cd4-8cc6-e99bb49498c5

As I understand, negative lookahead should check if a group (e06772ed-7575-4cd4-8cc6-e99bb49498c5) has a match, or am I incorrect?

Since input string has a group match, why does negative lookahead not work? By that I mean that I expect my regex to e06772ed-7575-4cd4-8cc6-e99bb49498c5 to match input string e06772ed-7575-4cd4-8cc6-e99bb49498c5.

Removing negative lookahead makes this regex work correctly.

Tested with regex101.com

Upvotes: 0

Views: 91

Answers (1)

Marc Lambrichs
Marc Lambrichs

Reputation: 2882

The takeway message of this question is: a lookaround matches a position, not a string.

(?!e06772ed-7575-4cd4-8cc6-e99bb49498c5)

will match any position, that is not followed by e06772ed-7575-4cd4-8cc6-e99bb49498c5.

Which means, that:

^\/admin\/(?!(e06772ed-7575-4cd4-8cc6-e99bb49498c5)).*$

will match:

/admin/abc

and even:

/admin/e99bb49498c5

but not:

/admin/e06772ed-7575-4cd4-8cc6-e99bb49498c5/daffdakjf;adjk;af

This is exactly the explanation why there is a match whenever you get rid of the ?!. The string matches exactly.

Next, you can lose the parentheses inside your lookahead, they do not have their usual function of grouping here.

Upvotes: 1

Related Questions