IP Address regex

Newb Newb wrote:

Hi..

I want to check for correct ip address while i submit the form.
When i used below regular expression.it accepts 0.0.0.0 as ip address
value.
REGEXP_HOST_ADDRESS
=/\A(?:25[0-5]|(?:2[0-4]|1\d|[1-9])?\d)(?:\.(?:25[0-5]|(?:2[0-4]|1\d|[1-9])?\d)){3}\z/.
But in my case it's not a valid ip address.

so Pls help me with your assistance
  

I'd try breaking it up a bit, and resolving this in stages.

It looks like you're searching for string start, expr.expr.expr.expr, string end. The expr seems to be the same for each part, so if you solve it once then you can use it multiple times.

The (?:slight_smile: creates a grouping without back references, which shouldn't change the matching pattern, so I'll ignore it for now. This makes your base expression

(25[0-5]|(2[0-4]|1\d|[1-9])?\d)

I think your problem is operator precedence and grouping. I'll put in some more parentheses and some text to indicate how this expression is being parsed:

( (25[0-5]) or ( maybe one of these ( (2[0-4]) or (1(any digit)) or (1-9) ) and regardless then one of any digit ) )

broken down even further:

(one of 250,251,252,253,254,255)
or
( ( ( one of 20,21,22,23,24 or one of 10,11,12,13,14,15,16,17,18,19 or one of 1,2,3,4,5,6,7,8,9) or nothing) and 0,1,2,3,4,5,6,7,8,9)

put together, it looks like this matches everything from 0 to 255, which means 0.0.0.0 will match when you put 4 in a row. This may be more what you're looking for:

([1-9]|1\d\d?|2[0-4]\d|25[0-5])

which matches (1 to 9) or (10 to 199) or (200-249) or (250-255). If you want to include 0 simply change the initial [1-9] to \d. E.g. matching any IP that doesn't start with "0." would be:

REGEXP_HOST_ADDRESS = /\A(?:[1-9]|1\d\d?|2[0-4]\d|25[0-5])(?:\.(?:\d|1\d\d?|2[0-4]\d|25[0-5])){3}\Z/

    -Chris