re.compile and very specific searches

Diez B. Roggisch deetsNOSPAM at web.de
Fri Feb 18 13:35:24 EST 2005


rbt wrote:

> Is it possible to use re.compile to exclude certain numbers? For
> example, this will find IP addresses:
> 
> ip = re.compile('\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}')
> 
> But it will also find 999.999.999.999 (something which could not
> possibly be an IPv4 address). Can re.compile be configured to filter
> results like this out?

You could use another regular expressin, e.g. like this:

import re

rex = re.compile(r"^((\d)|(1\d{1,2})|(2[0-5]\d))$") 

for i in xrange(1000):
    m = rex.match(str(i))
    if m:
        print m.groups(), i


This is of course only for one number. Extend it accordingly to the ip4
address format.

However, you won't be able to suppress the matching of e.g. 259 by that
regular expression. So I'd suggest you dump re and do it like this:

address = "192.168.1.1"

def validate_ip4(address):
    digits = address.split(".")
    if len(digits) == 4:
        for d in digits:
            if int(d) < 0 or int(d) > 255:
                  return False
    return True

-- 
Regards,

Diez B. Roggisch



More information about the Python-list mailing list