huan feng
huan feng

Reputation: 8623

How to use a Regex to check URL should begin & end with expected pattern

I want to check if URL is valid to match below pattern.

https://xxx.abc.com/yyy/?&p=1000/1001

How can i write the Regex to achieve?

Expected:

  1. Starts with domain 'https://xxx.abc.com', 'xxx' could be any name of sub-domain, 'abc.com' should be fixed value.

  2. Path /yyy could be any path, even sub-path should be allowed. https://xxx.abc.com/yyy/?&p=1000/1001

  3. ?&p=1000/1001 should be ok with '\?(\&)?p=\d+/\d+'

Upvotes: 1

Views: 957

Answers (4)

Hackoo
Hackoo

Reputation: 18857

You can divide your regex into two groups :

^(https:\/\/[a-z0-9]+\.abc\.com)(\/.*\?\&?p=\d+\/\d+)$

1 - The first group starts with domain https://xxx.abc.com

2 - The second group is the sub-path like /yyy/?&p=1000/1001

Demo here

Upvotes: 1

Golam Mazid Sajib
Golam Mazid Sajib

Reputation: 9457

Try with this: ^https:\/\/\w+\.abc\.com\/[\w\/-]+\?\&?p=\d+\/\d+$

Demo here

Upvotes: 1

Joundill
Joundill

Reputation: 7594

/https:\/\/[a-z0-9]+\.abc\.com\/.*\?(\&)?p=\d+\/\d+/i

Upvotes: 1

Ofer Tal
Ofer Tal

Reputation: 11

Since you didn't specify any restrictions on xxx or yyy, I'm going to assume they should conform to something reasonable such as "1 or more alphanumeric characters or a dash/hyphen" or in regex: [a-bA-B0-9\-]+ feel free to adjust that to anything else in the regex:

^https:\/\/[a-bA-B0-9\-]+\.abc.com/[a-bA-B0-9\-]+\/\?(\&)?p=\d+/\d+$

breaking it down:

  • the ^ in the start and the $ in the end are important because they make sure the regex matches the entire string you pass it (^ binds to the beginning of the input string and $ binds the end) without those, you might match any string that contains the URL as a substring
  • the [a-bA-B0-9\-]+ parts, as mentioned above match any sequence of alphanumeric or - characters. Note that if you are using a regex framework that allows you to run the regex case insensitive (e.g. a perl/javascript like regex /regex/i or in c# using RegexOptions.IgnoreCase) you can safely change this to [a-b0-9\-]+
  • the rest is pretty self explanatory I believe...

Upvotes: 1

Related Questions