Jake
Jake

Reputation: 4234

Regex: Matching one substring, but excluding another substring later on

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:

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.

Upvotes: 0

Views: 71

Answers (3)

user1636522
user1636522

Reputation:

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

Upvotes: 0

anubhava
anubhava

Reputation: 784928

You're close. Try this regex:

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

Upvotes: 0

Jon
Jon

Reputation: 437336

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.

Upvotes: 3

Related Questions