Sahil Sharma
Sahil Sharma

Reputation: 4217

Regex to match only specific type of URLs?

I want to create regex for URLs of type:

/m/abc/xyz/

The above URL should always start with /m/ but abc could be any text followed by a forward slash. Also xyz could be any text followed by a forward slash. The string should end with this forward slash.

For example, /m/abc/xyz/pqr/ is not a match.

I tried using \/m\/.+\/.+\/$ but it is even matching /m/abc/xyz/pqr/. How do I generate regex for this? Is there any tool where I can put my strings that should match and string that shouldn't and it returns me the regex for it.

Upvotes: 0

Views: 165

Answers (3)

The Scientific Method
The Scientific Method

Reputation: 2436

The problem with your regex is that it is greedy(+) eating everything it can, so make it not greedy to make it work,

try this one

\/m\/.+?\/.+?\/

try demo here

Upvotes: 0

Phillip
Phillip

Reputation: 817

there you go:

\/[a-z]\/[a-z]{3}\/[a-z]{3}\/$

Upvotes: 0

Ethan
Ethan

Reputation: 4375

Try this: \/m\/[^\/]+\/[^\/]+\/$

regex101 demo

The problem with your current regex is that . matches everything, so the second .+ is probably matching xyz/pqr. Using [^\/] matches everything except slashes, so it doesn't spill over.

Upvotes: 2

Related Questions