regular expressions and matches

johnzenger at gmail.com johnzenger at gmail.com
Thu Mar 30 07:10:45 EST 2006


Johhny wrote:
> Hello,
>
> I have recently written a small function that will verify that an IP
> address is valid.
>
> ==SNIP==
>
> import re
> ipAddress = raw_input('IP Address : ')
>
> def validateIP(ipAddress):
>         ipRegex =
> r"^([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])$"

Good lord!  You might as well be writing in assembly!  The re module
docs should include a customer warning label.

Regular expressions are not the answer here.  Probably 80% of the regex
virus could be stamped out if people used split instead.  How about
something simpler, like this:

def ipValid(ipAddress):
    dots = ipAddress.split(".")
    if len(dots) != 4:
        return False
    for item in dots:
        if not 0 <= int(item) <= 255:
            return False
    return True

...although even this function (like yours) will declare as "valid" an
IP address like 0.255.0.0.

For a real-world application, how about:

import socket
try:
    mm = socket.inet_aton(ipAddress)
    return True # We got through that call without an error, so it is
valid
except socket.error:
    return False # There was an error, so it is invalid


>         re_ip = re.compile(ipRegex)
>         match = re_ip.match(ipAddress)
>         if not match:
>                 print "an error has occured with ipAddress"
>                 return match
>         else:
>                 return match
>
> print(validateIP(ipAddress))
>
> ==SNIP==
>
> I was having issues trying to get my code working so that I could pass
> the IP addresses and it would return a true or false. When it matches I
> get something that looks like this.
>
> python ip_valid.py
> IP Address : 192.158.1.1
> <_sre.SRE_Match object at 0xb7de8c80>
>
> As I am still attempting to learn python I am interested to know how I
> could get the above to return a true or false if it matches or does not
> match the IP address. I would also like to expand that so that if the
> IP is wrong it requests the IP address again and recalls the function.
> I have done the same thing in php very easily but python appears to be
> getting the better of me. Any assistance and advice would be greatly
> appreciated.
> 
> Regards,
> 
> Johhny




More information about the Python-list mailing list