Regex to include certain words but exclude another
regex
Solution
In a single regex you can use negative lookahead:
^(?!.*\/thank-you(?:\/|$))(?:.*\/)?(?:contact-us|register-now)\/
RegEx Demo
- `(?!.*\/thank-you(?:\/|$))` is negative lookahead that will fail the match if URL has `/thanks-you` or `/thank-you/`.
- Use `MULTILINE` mode if your text contains multiple URLs in each line.
Problem
I am trying to write a regular expression which will check a URL contains certain words and excludes another. The reason for this is I am trying to track traffic moving through my website and I don't want to count anyone who hits the Thank You page. So for example: - `http://www.mywebsite.com/register-now/` - MATCH - `http://www.mywebsite.com/contact-us/` - MATCH - `http://www.mywebsite.com/register-now/thank-you` - NO MATCH - `http://www.mywebsite.com/contact-us/thank-you` - NO MATCH - `http://www.mywebsite.com/thank-you` - NO MATCH I have 2 words (`register-now` and `contact-us`) these must be in the URL. However I must ensure that 1 word (`thank-you`) is also not in the URL. I have tried to use a negative lookahead to check that the URL does NOT contain thank-you but It is not working: ``` "^(?!.*\/thank\-you+)\/(contact\-us|register\-now)\/.*" ```