regular expressions and matches

J

Johhny

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
 
F

Fredrik Lundh

Johhny said:
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.

you can use the return value right away. the match function/method
returns None if it fails to find a match, and None is treated as a false
value in a "boolean context":

http://docs.python.org/ref/Booleans.html

if you get a match instead, you get a match object (SRE_Match),
which is treated as True.

if you really really really want to return True or False, you can do

result = bool(re.match(...))

</F>
 
B

bruno at modulix

Johhny said:
Hello,

I have recently written a small function that will verify that an IP
address is valid.

(snip re.match() based solution - just one remark: compiling the regexp
on each function call is more than useless)
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.

If you re-read the fine manual, you'll notice that re.match() returns
either None or a Match object. Since, in a boolean context, None evals
to False and a Match object to True, just convert the return of re.match
to a boolean:

return bool(re_ip.match(ipAddress))

BTW, don't mix outputs and a logic. Your validateIp() function should
*only* validate, not print anything (except for debugging purpose, but
then it should either go to a log or at least to stderr, stdout is for
normal program outputs).
I would also like to expand that so that if the
IP is wrong it requests the IP address again and recalls the function.

Then wrap the raw_input()/validateIp() into a loop. And wrap this loop
into a function !-)

def get_valid_ip(prompt="please enter an ip",
errormsg="Sorry, %s is not a valid ip"):
while True:
ip = raw_input("%s : " % prompt).strip()
if validateIp(ip):
return ip
else:
print errormsg % ip

ip = get_valid_ip()

I have done the same thing in php very easily but python appears to be
getting the better of me.

Knowledge doesn't map one-to-one from one language to another.
 
J

johnzenger

Johhny said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top