Jitan Gupta
Jitan Gupta

Reputation: 484

After matching a pattern ignore remaing blocks of string (URLs) using REGEX

I am having few URLs as below and I want to check whether they match a regex or not.

URLs

https://www.amazon.in/Fire-Boltt-Display-Sports-Smartwatch-Tracking/dp/B09YV4RG4D
https://www.amazon.in/Fire-Boltt-Display-Sports-Smartwatch-Tracking/dp/B09YV4RG4D/
https://www.amazon.in/Fire-Boltt-Display-Sports-Smartwatch-Tracking/dp/B09YV4RG4D?tag=goog-21&linkCode=ogi&th=1&psc=1
https://www.amazon.in/dp/B087FXHB6J?tag=goog-21&linkCode=ogi&th=1&psc=1
https://www.amazon.in/dp/B087FXHB6J

Regex

/(https:\/\/www.amazon.in\/)([A-Za-z0-9-_]{0,}\/?)(dp\/[a-zA-z0-9]{0,})(\/?)(\??)/gm

Here is the test results from browser console enter image description here

and from https://regex101.com/ enter image description here

My question is, What I am doing wrong as 2nd and 4th scenarios are failing?

Upvotes: 0

Views: 42

Answers (1)

The fourth bird
The fourth bird

Reputation: 163362

If you need to check for a match only, you can match /dp/ as it is present in all the examples, and optionally match / or ? at the end of the pattern followed by optional non whitespace characters.

^https:\/\/www\.amazon\.in(?:\/[\w-]*)*\/dp\/[a-zA-z0-9]+(?:[\/?]\S*)?$

regex demo

Upvotes: 1

Related Questions