keeehlan
keeehlan

Reputation: 8054

Modify RegEx to match both hostname and port number?

I found this Regular Expression:

^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$

It's supposed to match any hostname, however I need it to also match a colon followed by a port number at the end, like this:

host.name.com:8888

How can I modify this expression to do what I need?

Upvotes: 0

Views: 2044

Answers (3)

keeehlan
keeehlan

Reputation: 8054

This is the RegEx I came up with for my C# application:

@"^(?<hostname>((?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?)|localhost)(?::(?<port>\d+))$"

Upvotes: 1

Sam
Sam

Reputation: 2970

Don't use regex, use TcpClient

static bool checkHost(string host,int timeout)
{
    if (!host.Contains(':')) 
        return false;
    try
    {
        string[] h = host.Split(':');
        Task e = new TcpClient().ConnectAsync(h[0], int.Parse(h[1]));
        new Task(e.Start);
        Thread.Sleep(timeout);

        return e.IsCompleted;
    }
    catch (SocketException){ }
    catch (ArgumentOutOfRangeException) { }

    return false;
}

Example

bool check = checkHost("google.com:80",1000);

Upvotes: 1

Thorsten Sch&#246;ning
Thorsten Sch&#246;ning

Reputation: 3728

You may simply change the end from $ to (?::[\d]+)?$ You can easily test such things with online reg exp matchers or QuickREx, which is a tool I prefer.

Upvotes: 0

Related Questions