Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re^3: IPv4 regex

by AnomalousMonk (Archbishop)
on Jul 22, 2016 at 20:47 UTC ( [id://1168391]=note: print w/replies, xml ) Need Help??


in reply to Re^2: IPv4 regex
in thread IPv4 regex

Please also see Regexp::Common and Regexp::Common::net.

c:\@Work\Perl\monks>perl -wMstrict -le "use Test::More 'no_plan'; use Test::NoWarnings; ;; VECTOR: for my $ar_vector ( [ '1.133.123.123', 1 ], [ '1.2.3.4', 1 ], [ '11.22.33.44', 1 ], [ '0.0.0.0', 1 ], [ '255.255.255.255', 1 ], [ '', '' ], [ '1asdf1.133.123.123', '' ], [ '12341.133.', '' ], [ '0.0.0.256', '' ], [ 'not at all valid', '' ], [ '1.2.3.4.5', '' ], [ '1111.2.3.1111', '' ], ) { my ($ip, $valid) = @$ar_vector; ;; my $status = $valid ? 'valid' : 'INVALID'; is IP_valid($ip), $valid, qq{'$ip' $status}; } ;; done_testing; ;; ;; use Regexp::Common qw(net); ;; sub IP_valid { my ($ip) = @_; return $ip =~ m{ \A $RE{net}{IPv4} \z }xms; } " ok 1 - '1.133.123.123' valid ok 2 - '1.2.3.4' valid ok 3 - '11.22.33.44' valid ok 4 - '0.0.0.0' valid ok 5 - '255.255.255.255' valid ok 6 - '' INVALID ok 7 - '1asdf1.133.123.123' INVALID ok 8 - '12341.133.' INVALID ok 9 - '0.0.0.256' INVALID ok 10 - 'not at all valid' INVALID ok 11 - '1.2.3.4.5' INVALID ok 12 - '1111.2.3.1111' INVALID 1..12 ok 13 - no warnings 1..13
Note that, by design,  $RE{net}{IPv4} is not "anchored", so by itself it will match, e.g.:
c:\@Work\Perl\monks>perl -wMstrict -le "use Regexp::Common qw(net); ;; print qq{matches IP of '$1'} if '99999.1.2.9999' =~ m{ ($RE{net}{IPv4}) }xms; " matches IP of '99.1.2.99'
which may or may not be what you want. The  \A \z anchors in the example code above address this (quite intentional) feature.


Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1168391]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (3)
As of 2024-04-20 02:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found