In the following ip address validation i want to see if it a valid ip address or not how can i do this using the below re
>>> ip="241.1.1.112343434"
>>> aa=re.match(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}[^0-9]",ip)
>>> aa.group()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
Use anchors instead:
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:
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:
Here, the
\bword boundary anchors make sure that the digits don’t exceed 3 for each segment.