re Challenge: More Compact?

Tim Hammerquist tim at vegeta.ath.cx
Sun Jul 15 20:58:46 EDT 2001


Tim Daneliuk <tundra at tundraware.com> wrote:
> The following re is (I think) the description of a legitimate IP addess in
> "quad" format (IPV4).  My question is, can it be made even shorter?
> 
> ipquad   = r"^((\d\d?\d?\.){3}(\d\d?\d?))$"

from 'Mastering Regular Expressions', p.124:

'^([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])$'

The author's own words below the result:
    "Quite a mouthful! Was the trouble worth it? ..."

It's not compact, and it's certainly not the only way to do it, but it
performs the 0-255 test within the regex.

A later suggestion in the same chapter:

'^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$'

(capturing parens) for easy subsequenst validation.

Easily implemented in Perl:

: sub valid_ip {
:     my ($ip, $failed, @elements) = (shift, 0);
:     @elements = ($ip =~ /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
:     $failed = grep { $_ > 255 } @elements;
:     return ($failed) ? undef : 1;
: }

Slightly more verbose in Python:

: import re
: def valid_ip(ip):
:     expr = r'^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$'
:     elements = map(int, re.match(expr, ip).groups())
:     failed = filter(lambda x: x > 255, elements)
:     if failed:  return None
:     else:       return 1

Please excuse the enthusiastic and unnecessary coding. It sounded like
fun!

HTH
-- 
Destinations are often a surprise to the destined.
    -- Thessaly, The Sandman



More information about the Python-list mailing list