fatman45
fatman45

Reputation: 68

Extract subdomain from url using regex

I've searched through all of the related topics here but none seems to answer my specific need. Here is the problem: Given a URL (sans protocol), I want to extract the subdomain portion, excluding www. The domain portion is always the same so I don't need to support all TLDs. Examples:

www.subdomain.domain.com should match subdomain
www.domain.com should match nothing
domain.com should match nothing

This is one of the many iterations I have tried:

[^(www\.)]\w+[^(\.domain\.com)]

Upvotes: 0

Views: 1719

Answers (1)

Jerry
Jerry

Reputation: 71538

Square brackets indicate character class and will remove all the order of otherwise special meaning of most characters.

You can try something like this instead:

((?:[^.](?<!www))+)\.domain\.com

regex101 demo

To return what you're looking for instead of retrieving it through submatches:

((?:[^.](?<!www))+)(?=\.domain\.com)

regexp101 revised

Upvotes: 2

Related Questions