I would like to have a regex that matches both of the following examples:
http://testsite.com/1234/MyPage
http://testsite.com/MyPage
The following examples should however not match:
http://testsite.com/
http://testsite.com/anything/MyPage
Thanks!
You can use the following regular expression:
^http:\/\/testsite\.com(?:\/1234)?\/MyPage$
And here is a live example: https://regex101.com/r/eu6HdA/4
If you want to have a list of allowed subpages, you can use the following regular expression:
^http:\/\/testsite\.com(?:\/(?:1234|4567|7890))?\/MyPage$
Live example: https://regex101.com/r/eu6HdA/5
Explanation:
^
start of the stringhttp:\/\/testsite\.com
escaping with \
is necessary for special regex characters(?:\/1234)?
match an optional non-matching group of /1234
(?:\/(?:1234|4567|7890))?
match an optional non-matching group with /
and the one of the following 1234
, 4567
or 7890
$
end of the string