Wilson
Wilson

Reputation: 31

Regex to match a pattern and exclude list of string

I am pretty new with Regex.

Basically I am trying to create a regex to assess the URL path from our system. However, there is a known bug in our system which causing the URL path become really messy..

Ideally, the URL should be

/mobile/retail.*

Due to the bug, the URL will have ‘something else’ in between the ‘/mobile’ and ‘/retail’ something like this

/mobile(/.*)?/retail

But the challenging bit is when there is some words that I would like to ignore in that ‘something else’ i.e. sale, search, lot, login. So the case should look like this

So I have a test case like this:

I am kinda stuck with this regex and it is not working as how I want it..

/mobile(/(?!sale|search|lot|login).*)?/retail.*

The regex above does not work in the condition such:

The word to exclude is strict. For example, the below list should pass:

Anyone with a strong regex knowledge and any feedback is much appreciated.

Upvotes: 3

Views: 8114

Answers (2)

Sjoerd
Sjoerd

Reputation: 75609

A regex that matches parts between slashes repeatedly, where such a part may not be sale, search, lot, or login:

^/mobile(/(?!sale|search|lot|login)[^/]*)*/retail.*

Upvotes: 2

Tim Pietzcker
Tim Pietzcker

Reputation: 336178

First try this:

/mobile(?:/(?:(?!sale|search|lot|login)[^/])++)*/retail.*

If that fails to compile (you didn't specify your regex flavor), try

/mobile(?:/(?:(?!sale|search|lot|login)[^/])+)*/retail.*

Explanation:

/mobile                     # Match "/mobile"
(?:                         # Match...
 /                          # a slash
 (?:                        # followed by...
  (?!sale|search|lot|login) # (only if these strings arent't present
  [^/]                      # any character except slashes
 )++                        # Match at least one and don't backtrack
)*                          # Do this zero or more times
/retail                     # Then match "/retail"
.*                          # plus whatever follows

Upvotes: 6

Related Questions