Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex to match optional or fixed subdomain, with optional www, fixed domain

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading