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:  <%-{-{-{-<


In reply to Re^3: IPv4 regex by AnomalousMonk
in thread IPv4 regex by ryan

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.