0

Trying to write a regex that matches certain URLs. For our purposes, let's assume the URLs are:

http://website.com/Section/subsection/Cows
http://website.com/Section/Cows
http://website.com/Section/subsection/Chickens

I want to match:

  • URLs that contain /Section/
  • Unless it is followed by /Chickens

The closest I've gotten is /\/Section\/([a-zA-Z0-9]+)\/(?!Chickens)/gi

This works for the first URL, but the 2nd URL will not be matched. I know it is because it doesn't have the [a-zA-z0-9]+ section, but I don't know how to solve it.

2
  • 1
    url.indexOf('/Section') != -1 && url.indexOf('/Chickens') != -1 Commented Dec 19, 2013 at 19:40
  • Do you need to make sure that its a valid URL? If so, you will need a much larger regex. I would use someone else's URL matcher code and then do what @adeneo suggests. Commented Dec 19, 2013 at 20:14

3 Answers 3

3

You were quite close. Here is the regex:

\/Section\/(?!.*\/Chickens)

It just matches the section part and then asserts that anything followed by "/Chickens" cannot match going forward.

You can tail the regex off with an additional .* (outside the negative lookahead) if you want it to capture the URL path instead of just testing for a match.

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

Comments

0

You're close. Try this regex:

/\/Section\/([a-z0-9]+)(?!\/Chickens)/gi

Comments

0

This one rejects "/Section/Chickens" as well :

var r = /\/Section\/(?!(.+\/)*Chickens(\/|\?|#|$))/;
r.test('/Section/Cows'); // true
r.test('/Section/Chickens'); // false
r.test('/Section/CowsChickens'); // true
r.test('/Section/ChickensCows'); // true
r.test('/Section/Cows/Chickens'); // false
r.test('/Section/Cows/Cows/Chickens'); // false
r.test('/Section/Cows/Chickens/Cows'); // false

Comments

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.