Thursday, 19 June 2008

How do I remove the port number from a URL in C#.NET?

Regular Expression:

Using C#.NET, the above regular expression can be applied to a URL to strip the port number (along with ":"):

Regex regex = new Regex( @":{1}\d{1,}" );
string url = regex.Replace( "", string.Empty );


Anonymous said...

This code removes the colon from "http://" as well as the port.

Anonymous said...

This will do it:

Regex regex = new Regex(@":{1}[0-9]{1}\d*");
string uriLeftPart = regex.Replace(Context.Request.Url.GetLeftPart(UriPartial.Authority), string.Empty);
return uriLeftPart;

Andrew Gunn said...

Thanks for spotting that. I've changed the post but I've gone for a slighlty different expression: