0

I want a regular expression to match on paths containing '/food/' but not '/food/api/':

http://example.com/food/api/pasta?sauce=true

Right now I'm using this:

/^((?!\/food\/api\/).)*$/

The problem with this is it matches ANY path that doesn't contain '/food/api/'

Behavior I want to achieve:

REGEX MATCHES
example.com/food/
example.com/food/meals

REGEX IGNORES
example.com/food/api/pasta?sauce=true
example.com/food/api/pasta
example.com/food/api/
example.com/meal
example.com/

1 Answer 1

1

Using a pattern like this ((?!\/food\/api\/).)* (a tempered greedy token solution) will match the whole line if it does not contain the sub string /food/api

As the quantifier is a * it will also match an empty line.

Instead, you can use an alternation to match until the first occurrence of a / followed by food or meal followed and a forward slash. After this slash, check that it is not followed by /api

^[^/]+/(?:food|meal)/(?!api/).*$

Regex demo

If the string can not contains spaces, you can exclude them using the negated character class [^/\s]+ and match \S* instead of .*

^[^/\s]+/(?:food|meal)/(?!api/)\S*$

Regex demo

Sign up to request clarification or add additional context in comments.

2 Comments

What syntax would be needed to shorten this up so it does a 'contains' check instead of starts the string at 'http/s'?
@OP I have added an update. You can leave out the protocol in that case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.