keeehlan
keeehlan

Reputation: 8054

Need a Regular Expression to validate a hostname and port to be used with TcpClient.Connect()

The title pretty much says it all.

To clarify, the expression must match something like this:

127.0.0.1:8888

Or this:

localhost:8888

The hostname and port must be valid, but they also must be in a string that's constructed like the ones above, colon and all.

How can I accomplish this?

Upvotes: 0

Views: 2496

Answers (1)

User 12345678
User 12345678

Reputation: 7804

The following pattern should match either the a standard IPv4 address or the text 'localhost' as well as the port number.

public static bool IsValidHostAddress(string hostAddress)
{
    const string Pattern =  @"^(([0-9]{1,3}.){3}([0-9]{1,3})|localhost):\d+$";

    var regex = new Regex(Pattern, RegexOptions.Compiled);
    return regex.Match(hostAddress).Success;
}

Upvotes: 2

Related Questions