regular expressions and matches

Johhny exter_c at hotmail.com
Thu Mar 30 11:48:58 CEST 2006


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])$"
        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