Using a regex to match IP addresses in Python

Posted by MHibbin on Stack Overflow See other posts from Stack Overflow or by MHibbin
Published on 2012-06-29T14:50:46Z Indexed on 2012/06/29 15:16 UTC
Read the original article Hit count: 280

Filed under:
|

I'm trying to make a test for checking whether a sys.argv input matches the regex for an IP address...

As a simple test, I have the following...

import re

pat = re.compile("\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}")
test = pat.match(hostIP)
if test:
   print "Acceptable ip address"
else:
   print "Unacceptable ip address"

However when I pass random values into it, it returns "Acceptable ip address" in most cases, except when I have an "address" that is basically equivalent to \d+

Any thoughts welcome.

Cheers

Matt

© Stack Overflow or respective owner

Related posts about python

Related posts about regex