Use your imagination

Friday, September 22, 2006

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.

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.

kick it on DotNetKicks.com


  • At 7:26 PM, Blogger Pras said…

    coool, can you gimme ur template? I'm kinda finding hard to put those digg and all http://infinity-unbound.blogspot.com/

  • At 5:07 AM, Anonymous Sam Lad said…

    Hey, thanks for the code but it doesn't behave correctly for .co.uk domains...

    Regex.Replace("sales.testimonialmonkey.com", "((.*)(\\..*){2})|(.*)", "$2")

    returns sales which is correct, however...

    Regex.Replace("sales.testimonialmonkey.co.uk", "((.*)(\\..*){2})|(.*)", "$2")

    returns sales.testimonialmonkey


Post a Comment

Links to this post:

Create a Link

<< Home