Use anchors instead:
aa=re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$",ip)
These make sure that the start and end of the string are matched at the start and end of the regex. (well, technically, you don't need the starting ^
anchor because it's implicit in the .match()
method).
Then, check if the regex did in fact match before trying to access its results:
if aa:
ip = aa.group()
Of course, this is not a good approach for validating IP addresses (check out gnibbler's answer for a proper method). However, regexes can be useful for detecting IP addresses in a larger string:
ip_candidates = re.findall(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", ip)
Here, the \b
word boundary anchors make sure that the digits don't exceed 3 for each segment.