Hi, I've needed to validate user input to ensure it is a validly formatted IPv4 address.

The one I came up with before I looked around was:
/(^(\d{1,3}\.){3})\d{1,3}$/ The double brackets are to ensure the ^ stands for 1 triplet, not all three of them such as  (^\d{1,3}\.){3} which could never occur

Is there anything failsafe yet more efficient than this?

After hunting around I discovered suprisingly that many mail programs and even the LRP favour using this regex:
/^\d+\.\d+\.\d+\.\d+$/ Which will fail on things like 1111.0.0.0

As a side note, I'm sure there is a way to compare two variables to the same regex in one neat expression rather than
if ($var1 =~ /$regex/&&$var2 =~ /$regex/) I guess for an array a foreach can be used, but just for 2 variables only is there a way?

Thanks folks.


In reply to 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.