-3

For port number testing purpose I am passing the following URL, but it throws an exception, exception itself is null - no descriptive information

testURL = "ce-34-54-33.compute-1.amazonaws.com:";

Regex r = new Regex(@"^(?<proto>\w+)://[^/]+?:(?<port>\d+)?/",
RegexOptions.None, TimeSpan.FromMilliseconds(150));
// the following throws an exception
int port = Int32.Parse(r.Match(testURL).Result("${port}"));

enter image description here

enter image description here

Update:

If I use System.Uri, the value always -1 no matter whether or not I include port.

Uri uri = new Uri(connectionURL);
int value = uri.Port;
casillas
  • 16,351
  • 19
  • 115
  • 215

1 Answers1

1

The exception you get is:

System.NotSupportedException: 'Result cannot be called on a failed Match.'

Your testURL doesn't contain a port, so the named group "port" didn't match anything. It also doesn't contain a "proto", which isn't marked optional, so the entire regex has no matches. Finally, it doesn't end in the required slash.

So fix your input:

var testURL = "https://ce-34-54-33.compute-1.amazonaws.com:443/";

Regex r = new Regex(@"^(?<proto>\w+)://[^/]+?:(?<port>\d+)?/");

var port = int.Parse(r.Match(testURL).Result("${port}"));

And you'll see it works just fine.

Of course this code still needs additional error handling:

var testURL = "https://ce-34-54-33.compute-1.amazonaws.com:443/";

Regex r = new Regex(@"^(?<proto>\w+)://[^/]+?:(?<port>\d+)?/");

var match = r.Match(testURL);

var portGroup = match.Groups["port"];
int port = -1;

if (portGroup.Success)
{
    if (!int.TryParse(portGroup.Value, out port))
    {
        port = -1;
    }
}

This sets the port to -1 if none is present in the input URL.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • `var testURL = "https://ce-34-54-33.compute-1.amazonaws.com:8` does not pick up the right port number, it still returns `{}` – casillas Jul 10 '17 at 21:40
  • That's because the URL must end in a slash, as dictated by your regex. – CodeCaster Jul 10 '17 at 21:40
  • Any idea for the following https://stackoverflow.com/questions/45022396/url-well-formed-returns-true-for-invalid-url – casillas Jul 10 '17 at 22:07