How to extract the subdomain from a URL in C# using regular expressions
I recently read a post with some C# code for extracting a subdomain from a URL at Mads Kristensen's blog. Since I am currently working on something where I needed to do the same I decided to share the method I came up with using a regular expression. Here it is for my own and others reference.
An item to note with this is if your are looking for better performance I'd suggest creating a static Regex member variable instead of using the static Replace method as I am here.
private static string GetSubDomain(Uri uri)
{
string host = uri.Host;
string subdomain = null;
if (uri.HostNameType == UriHostNameType.Dns)
{
subdomain = Regex.Replace(host, "((.*)(\\..*){2})|(.*)", "$2");
}
return subdomain;
}
An item to note with this is if your are looking for better performance I'd suggest creating a static Regex member variable instead of using the static Replace method as I am here.