There have been a number of pages around T'internet on regexps for determining an IP number, and I needed a slight variation.... which has led me to a really natty regexp for the base use-case:

chomp $ip; my $quad = '([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])'; if ($string =~ /^(${quad}\.){3}${quad}$/) { ## have valid IP }

All previous examples have been long strings defining each quad separately... I use two simple tricks:

  1. use variable substitution for the actual pattern, and
  2. use the repeat operator to define three repeats of the first section

oh... and ${quad} is just a way of ensuring that the right variable name is used... a-la $foo = "${bar}barella" looks for $bar and appends barella to it


In my case, I wanted to try to guess between a (partial) IP number, a hostname, or some other string (a name) - so I have:

# $q contains the string to test my $quad = '([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])'; given ($q) { when ( # Is it an IP? # matches 127 or 127. or 127.0 or 127.0. or... # does not match any quad above 255, or 127.0.0.1. # as the fifth dot fails the match /^((${quad}\.){0,2}${quad}\.?|(${quad}\.){3}${quad})$/ ) { $type = 'ip'; } ## end when ( ...) when (/\w+\.\w+/) { # Is it a domain name? # words.words $type = 'url' } default { $type = 'name' } # it must be a name then... } ## end given


-- Ian Stuart
A man depriving some poor village, somewhere, of a first-class idiot.

In reply to Checking for a valid IP number by kiz

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.