Regex to match all subpaths except a list but not the base path

Viewed 50

I'm trying to write a regular expression to match all subpaths under a given path with a handful of exceptions.

The regex:

^\/my-page\/(?!.*foo|bar|baz).*

Expected behavior:

/my-page/thing1 - match!

/my-page/another-thing - match!

/my-page/foo - no match

/my-page/bar - no match

/my-page/baz - no match

This works as expected ✅

The problem:

The base path is also matched:

/my-page/ - match... but I don't want this to match. ❌

How can I adjust the regex expression to prevent /my-page/ from matching also?

1 Answers

You can use

^\/my-page\/(?!.*(?:foo|bar|baz)).+

See the regex demo.

Details

  • ^ - start of string
  • \/my-page\/ - /my-page/ string
  • (?!.*(?:foo|bar|baz)) - a negative lookahead that fails the match if there is foo, bar or baz after any zero or more chars other than line break chars as many as possible
  • .+ - one or more chars other than line break chars, as many as possible.
Related