MHibbin MHibbin - 3 months ago 18
Python Question

Using a RegEx to match IP addresses in Python

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"
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


You have to modify your regex in the following way

pat = re.compile("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$")

that's because . is a wildcard that stands for "every character"