in reply to Clarify this Regular Expression

The pattern could also be reduced to
/^(\d{1,3}\.){3}\d+/
Not for the sake of golfing, but it seems to me easier to read and more obvious what it is matching.

Replies are listed 'Best First'.
Re: Re: Clarify this Regular Expression
by tachyon (Chancellor) on Aug 17, 2001 at 03:34 UTC

    For efficiency you should avoid the capture of the parentheses like /^(?:\d{1,3}\.){3}\d+/ as you don't use the result. Here is a simple more accurate way to look for IPs. We just capture each of the 4 bytes into $1-$4 and can then test them however we like. Here we just see they are <256 but you could require say $1 to be 10 or whatever.

    while(<DATA>) { if (/(\d+)\.(\d+)\.(\d+)\.(\d+)/) { print "$1.$2.$3.$4 "; if ($1<256 and $2<256 and $3<256 and $4<256) { print "is IP\n"; } else { print "is not an IP\n"; } } } __DATA__ 0.0.0.0 255.255.255.255 1.2.3.4 256.1.1.1

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

      You are very correct, there is no reason to capture the result via parentheses in my version.