in reply to Validate Ip address Regexp

Regular expression is the wrong approach IMHO. The IPv4 address consists of four bytes (0..255) separated by dots.
Have a loock at split and pack. If you pack the byte values and unpack them again and assemble the IP string, origin and result should be equal if the origin is a valid IP address.

print "Enter IP Address:"; chop(my $ip = <STDIN>); my $parsed = join'.', unpack "C4", pack "C4", split/\./, $ip; if ($parsed eq $ip) { print "yes match $parsed\n"; } else { print "no match: parsed $parsed <> input $ip\n"; }

This of course doesn't work for IP addresses written with leading zeroes e.g 001.012.013.225 - which I consider bad practice anyways, because in my book a leading zero marks an octal value.

If you want to be absolutely sure, you can isolate the four bytes with a regular expression limiting each string representation to 3 chars of type number, i.e (\d{3]), then run the four values through pack/unpack as described above. There are many other ways to do this task...

perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'

Replies are listed 'Best First'.
Re^2: Validate Ip address Regexp
by Laurent_R (Canon) on Nov 28, 2015 at 22:53 UTC
    Regular expression is the wrong approach IMHO.
    Well, quite possibly, but the OP wanted to practice regular expressions (which is why I gave a pure regex solution) and, besides, using split is in fact using regular expressions.

    But I agree that checking for numbers in the 0-255 range with a pure regex is somewhat unwieldy. An easier way might be something along these lines:

    print "Valid IP\n" if 4 == grep { /^\d+$/ and $_ < 256 } split /\./, $ +ip;
    (although this is still not entirely satisfactory, since this would validate something like "23.45.aa3.234.244"", so a bit more effort might be needed).

    Note that Perl 6's regexes allow a code assertion to be inserted within a regex, leading for example to something like this:

    my regex octet {(\d ** 1..3) <?{0 <= $0 <= 255 }> } my regex ip {^ <octet> ** 4 % '.' $}