fatman45
fatman45

Reputation: 68

How do I return the subdomain from a URL using a regular expression?

I thought this would be something simple to do with regular expressions but so far the solution is proving to be elusive. Here is the scenario - I want to capture the subdomain portion of a URL but not "www." if it exists, e.g. assuming either of these URLs

www.mysubdomain.mydomain.com
mysubdomain.mydomain.com

I want the expression to return only mysubdomain - no dots!

Upvotes: 0

Views: 1801

Answers (1)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89547

If the language you use support lookbehind you can use this:

(?<=^www\.|^)[^.]+

If it doesn't, use this:

^(?:www\.)?([^.]+)

and your result is in the first capturing group, example in javascript:

var mystring = 'www.mysubdomain.mydomain.com';
var match = /^(?:www\.)?([^.]+)/.exec(myString);
console.log(match[1]);

Upvotes: 2

Related Questions