greener
greener

Reputation: 5069

Regular expression - extract subdomain when domain is unknown

I'm trying to use regex to get a subdomain when the domain name is unknown (and could be localhost). So far I have this but it fails the localhost requirement:

(.*?)\.(?=[^\/]*\..{2,5})|(?=localhost)

one.domain.com  //matches 'one' which is correct
one.localhost:8000  //no match, expecting 'one'
domain.com  //no match, as expected

DEMO

Upvotes: 1

Views: 621

Answers (2)

Marc Anton Dahmen
Marc Anton Dahmen

Reputation: 1091

Try this:

/([^.]+)\.([^.]+\.[^.]+|localhost)(?:[\d]+)?/

I would suggest to check in another step whether the matched subdomain equals www to keep the regex simple.

Upvotes: 0

Marcos Pérez Gude
Marcos Pérez Gude

Reputation: 22158

With this regular expression, you can obtain the first capturing group to obtain the subdomain:

/(.*?)\.(\w+)[\.|\:]([A-Za-z0-9]{3,4})/g

Test it:

https://regex101.com/r/rC0lO5/2

All green matches will be subdomains.

Update:

This updated regular expression will not match www.domain.com or domain.com as them have not subdomains:

/(.*?[^www])\.(\w+)[\.|\:]([A-Za-z0-9]{3,4})/g

https://regex101.com/r/rC0lO5/4

Upvotes: 1

Related Questions