Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match all subdomains of a matched domains

Tags:

java

regex

I have a Regex to match a subdomains of a web page like below

 "^https://[^/?]+\\.(sub1|sub2\\.)domain\\.com"

What would be the regex to accept any sub domain of domain.com.

Edit:

My question was incomplete, my regex was to accept only

 https:[any number of sub domain s ].sub1domain.com 

or

 https://[any number of sub domain s ].sub2domain.com

Sorry for posting incomplete question.

like image 639
Exception Avatar asked Oct 09 '13 13:10

Exception


3 Answers

This one should suit your needs:

https?://([a-z0-9]+[.])*sub[12]domain[.]com

Regular expression visualization

  • Visualization by Debuggex
  • Demo on RegExr
like image 135
sp00m Avatar answered Sep 16 '22 19:09

sp00m


I'm assuming that don't want the subdomains to differ simply by a number. Use this regex:

(^https:\/\/(?:[\w\-\_]+\.)+(?:subdomain1|subdomain2).com)

The single capture group is the full URL. Simply replace subdomain1 and subdomain2 with your actual subdomains.

I tested this on regex101.com

like image 30
fred02138 Avatar answered Sep 18 '22 19:09

fred02138


You would use

"^https://[^/?]+\\.([^.]+)\\.domain\\.com"

which boils down to matching

"[^.]+"

for any subdomain. will match only the last part of the subdomain (www.xxx.domain.com will capture "xxx" in group 1)

like image 26
AlexR Avatar answered Sep 16 '22 19:09

AlexR