I got this out of the Komodo help file:

IP addresses are difficult to match using a simple regular expression,
because the regular expression must verify that the IP address against which
it is matching is valid. A simple expression such as
/\d{3}\.\d{3}\.\d{3}\.\d{3}/  will incorrectly match strings such as
789.23.2.900, which is outside the range of valid IP addresses (i.e.,
0.0.0.0 to 255.255.255.255). Damian Conway's Regexp::Common
(http://velocity.activestate.com/code/search?query='Regexp::Common') module
provides a very effective regular expression which matches only valid IP
addresses.

Usage

#!/bin/perl
use Regexp::Common;

while(<DATA>) {
  if(/$RE{net}{IPv4}{dec}{-keep}/) {
    print "IP Address: $1\n";
  }
}

__DATA__
24.113.50.245
0.42.523.2
255.242.52.4
2.5.3

 -----Original Message-----
From:   Peter Scott [mailto:[EMAIL PROTECTED]]
Sent:   Thursday, June 14, 2001 3:54 PM
To:     Evgeny Goldin (aka Genie); [EMAIL PROTECTED]
Subject:        Re: regex matching

At 09:59 PM 6/14/01 +0200, Evgeny Goldin (aka Genie) wrote:

> > /(\d\d?\d?\.\d\d?\d?\.\d\d?\d?\.\d\d?\d?)/;
>
> >
>
/([01]?\d\d|2[0-4]\d|25[0-5])\.([01]?\d\d|2[0-4]\d|25[0-5])\.([01]?\d\d|2[0-
> > 4]\d|25[0-5])\.([01]?\d\d|2[0-4]\d|25[0-5])/)
>
>Wou ! Looks like too many symbols .. Does matching a legal IP worth
>a regex 1km long ? I think it's better to match the IP first,
>split /\./ it to four digits and check if their combination is legal -
>this will allow any sophisticated tests ( for 127.0.0.1 and the like ).
>
>Here's a regex which looks much shorter and flexible to me :
>
>C:\>perl -w
>my $line = 'here is a sample with 123.456.123.456 in the middle';
>my ($ip) = $line =~ m@((?:\d{1,3}\.){3}\d{1,3})@;
>print "[$ip]\n";
>^Z
>[123.456.123.456]

It's simply a matter of how pedantic you wish to be.  The example you
pasted is not a valid IP address (maximum component value is 255).

--
Peter Scott
Pacific Systems Design Technologies
http://www.perldebugged.com


Reply via email to