MojoDK
MojoDK

Reputation: 4538

Regex for IP address

I tried this code for validating IP address, but it doesn't work...

public static bool IP(string ipStr)
{
    string pattern = @"^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$";
    Regex check = new Regex (pattern);
    bool valid = false;
    if (ipStr == "") {
        valid = false;
    } else {
        valid = check.IsMatch (ipStr, 0);
    }
    return valid;
}   

Any idea what's wrong?

Upvotes: 10

Views: 30666

Answers (6)

Prabhanjan Naib
Prabhanjan Naib

Reputation: 201

Here is the complete regex for checking all possible IPv4 addresses (dotted decimal, dotted hexadecimal, dotted octal, decimal, hexadecimal, octal and mixed mode)

^(0[0-7]{10,11}|0(x|X)[0-9a-fA-F]{8}|(\b4\d{8}[0-5]\b|\b[1-3]?\d{8}\d?\b)|((2[0-5][0-5]|1\d{2}|[1-9]\d?)|(0(x|X)[0-9a-fA-F]{2})|(0[0-7]{3}))(\.((2[0-5][0-5]|1\d{2}|\d\d?)|(0(x|X)[0-9a-fA-F]{2})|(0[0-7]{3}))){3})$

I have tested it with all possible addresses.

Upvotes: 1

Alban
Alban

Reputation: 3215

for match a valid IP adress use

^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$

instead of

^([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])(\.([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-5])){3}$

because many regex engine match the first possibility in the OR sequence

you can try your regex engine : 10.48.0.200

test the difference here

Upvotes: 7

ern
ern

Reputation: 1512

There is a previously answered question available for a valid IP address.

As for debugging regular expressions, on Windows I heartily recommend Expresso. On the web, there is a free Flash-based tester available.

Upvotes: 2

L.B
L.B

Reputation: 116178

I would use IPAddress.TryParse static method instead.

IPAddress ip;
bool b = IPAddress.TryParse("1234.12.12.12",out ip);

Upvotes: 63

scartag
scartag

Reputation: 17680

I'm not really a regex expert per se but i use Expresso (a regex tool) and it has it's own regex library for pre-set scenarios like this. Try this below.

string pattern = @"(?<First>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?<Second>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?<Third>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?<Fourth>2[0-4]\d|25[0-5]|[01]?\d\d?)";

Upvotes: 1

Related Questions