Home > Back-end >  Regex to match optional or fixed subdomain, with optional www, fixed domain
Regex to match optional or fixed subdomain, with optional www, fixed domain

Time:02-23

I am trying get a regex to match a url with following rules:

  • https - mandatory
  • www - optional
  • subdomain, empty or any of sub1 and sub2
  • 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 - match
  • https://www.google.com - match
  • https://sub1.google.com - match
  • https://www.sub1.google.com - match
  • https://sub2.google.com - match
  • https://www.sub2.google.com - match
  • http:<anything> - do not match
  • https://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.

  • Related