-2

I want to parse the port number 5000 from this Url

var url = "http://localhost:5000"
Regex r = new Regex(@"^(?<proto>\w+)://[^/]+?(?<port>:\d+)?/",RegexOptions.None, TimeSpan.FromMilliseconds(150));
Match m = r.Match(url);

How to setup new Regex(@"^(?\w+)://[^/]+?(?:\d+)?/" this part to parse me just the portnumber "5000"?

  • 8
    Don't. Use the [Uri](https://docs.microsoft.com/en-us/dotnet/api/system.uri?view=net-6.0) class and it's [Port](https://docs.microsoft.com/en-us/dotnet/api/system.uri.port?view=net-6.0) property – MindSwipe May 23 '22 at 12:10
  • 1
    like that ? `code` var urlValue = "http://localhost:5000"; var url = new Uri(urlValue); Console.WriteLine("Host : {0}, Port {1} ", url.Host, url.Port); – SMCMario May 23 '22 at 12:14
  • Yup. [here](https://dotnetfiddle.net/MMMW0R)'s a demo – MindSwipe May 23 '22 at 12:16
  • thx it worked like a charm ^^ – SMCMario May 23 '22 at 12:29

0 Answers0