I'm terribly at regex and I could use some help in building a regular expression so that I can target all subroutes on a specific domain and at the same time exclude a couple of specific subroutes.
The regex is to be used in JavaScript (as page targeting within the Optimizely software).
Should allow:
www.mydomain.com/**/*
www.mydomain.com/foo/**/*
Should not allow
www.mydomain.com/foo/bar/**/*
www.mydomain.com/baz/**/*
The part I am most struggling with is allowing everything, also allowing everything ending with /foo/...
except when it is ending with /foo/bar/...
, while also excluding anything ending with /baz/...
.
Any help is much appreciated, thank you in advance!
CodePudding user response:
You can use a negative lookahead assertion to exclude specific patterns:
^www\.mydomain\.com\/(?!(?:foo\/bar|baz)\/).*\/.*
Demo: https://regex101.com/r/w6MQA0/1
CodePudding user response:
Use this (www.mydomain.com\/)(([a-z] \/)*(foo\/))?\*\*\/\*
. It should work.
It's working in this scenario:
`www.mydomain.com/**/*`
or
`www.mydomain.com/<any params may or may not be>/foo/**/*`
Code:
var regx = /(www.mydomain.com\/)(([a-z] \/)*(foo\/))?\*\*\/\*/g;
ar = ['www.mydomain.com/**/*', 'www.mydomain.com/foo/**/*','www.mydomain.com/foo/bar/**/*','www.mydomain.com/baz/**/*']
regx.test(ar[0]) // true
regx.test(ar[1]) // true
regx.test(ar[2]) // false
regx.test(ar[3]) // false
Demo: https://regex101.com/r/05vUz8/1
Other regex for referrance: