0
votes

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

1
You seem to need (?!.*e06772ed-7575-4cd4-8cc6-e99bb49498c5$)Wiktor Stribiżew
Not quite, your regex would match any user, my regex must match when it's admin and UID is the same, removing lookahead gives this result. But I can't figure out why (since it's supposed to work with lookahead).CrazySabbath
That's not clear: do you need to match /admin/e06772ed-7575-4cd4-8cc6-e99bb49498c5 or not?Wiktor Stribiżew
A negative lookahead asserts, that a certain pattern can't be matched from the curernt position, in your case e06772ed-7575-4cd4-8cc6-e99bb49498c5. As this assertion fails, the whole match is discarded.Do y ou need a positive lookahead maybe?Sebastian Proske
@Wiktor Stribiżew what's not clear? Let's say it's another user, user1/e06772ed-7575-4cd4-8cc6-e99bb49498c5 your regex would match both it and admin/e06772ed-7575-4cd4-8cc6-e99bb49498c5. That's incorrect.CrazySabbath

1 Answers

1
votes

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.