I am trying get a regex to match a url with following rules:
https
- mandatorywww
- optional- subdomain, empty or any of
sub1
andsub2
- domain - fixed, mandatory.
google.com
So far I got:
^https:\/\/(w{0,3})(sub1|sub2)\.google\.com$
Can't make it work to allow empty subdomain, i tried (^$|sub1|sub2)
in subdomain capturing group, but doesn't work. Also .
after www
or before domain name, it's conditional.
examples:
https://google.com
- matchhttps://www.google.com
- matchhttps://sub1.google.com
- matchhttps://www.sub1.google.com
- matchhttps://sub2.google.com
- matchhttps://www.sub2.google.com
- matchhttp:<anything>
- do not matchhttps://sub3.google.com
- do not match
CodePudding user response:
Try this: ^https:\/\/(w{0,3}\.)?(sub1\.|sub2\.)?google\.com$
Test here: https://regex101.com/r/imwunj/1
In your regex dots after www and sub's were not being matched, so once you make them optional, the regex works.