简体   繁体   中英

Regex to match subdomain (if exists) and domain (in nginx)

I need a regex to extract the subdomain (if it exists) and the domain with TLD. This is for an nginx config so please strictly regex is needed.

Examples:

www.a0.example.com 
www.example.com
www.example.org
  • Example line 1 should match a0 and example.com into groups
  • Example line 2 should match only example.com into a group since the subdomain is absent
  • Example line 3 should match only example.org into a group because the subdomain is absent as well

The group numbers should be consistant so $0 will always return the subdomain or blank if it does not exist, and $1 will always return the domain. The www will always be present.

Any regex wizards out there that can wave their wand?

This is a test regex in :

$ perl -lne '/^www\.([^\.]+\.)?([^\.]+\.[^\.]+)$/ and print "1=$1 2=$2"' file
1=a0. 2=example.com 
1=    2=example.com
1=    2=example.org

Regex :

/^www\.([^\.]+\.)?([^\.]+\.[^\.]+)$/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM