Max Favilli
Max Favilli

Reputation: 6449

regular expression matching a certain url

I hate posting questions like this one, but I really suck at regex and if an expert out there can give me a quick solution I would greatly appreciate it.

I need a regular expression to match a url pattern like this one

https://mywebsite.com/foo/[a-z]/[a-z]/[0-9]/[0-9]/[0-9]

Matching examples:

NOT matching examples:

HELP!

Upvotes: 0

Views: 60

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174864

Seems like you want something like this,

https:\/\/mywebsite\.com\/foo(?:\/[a-z]+){0,2}(?:\/[0-9]+){3}

Add anchors if necessary.

^https:\/\/mywebsite\.com\/foo(?:\/[a-z]+){0,2}(?:\/[0-9]+){3}$

DEMO

Range quantifier {0,2} in (?:\/[a-z]+){0,2} repeats the previous token that is /[a-z]+, zero or one or two times.

Upvotes: 2

neuhaus
neuhaus

Reputation: 4114

With "number" do you mean digit or number? I'm assuming you mean number.

This matches your request:

/^https:\/\/mywebsite\.com\/foo\/[a-z]*\/[a-z]*\/\d+\/\d+\/\d+$/

however when you write "1st and 2nd [a-z] are optional" I guess you mean the slashes that follow them should also be optional. If that's the case then use this:

/^https:\/\/mywebsite\.com\/foo\/([a-z]+\/)?([a-z]+\/)?\/\d+\/\d+\/\d+$/

The $ at the end makes sure that nothing else follows.

Upvotes: 0

Related Questions