[Python Patterns] Verify a list of IPv4 IP addresses
I like this one because of the obnoxious regex.
I like this one because of the obnoxious regex.
import re
def verify_ip_is_ip(ip_list):
""" Verifies each IP address in list, returns sanitized IP list """
# REGEX pattern to find/verify the IPs
regex_exp = r"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
new_sanitized_list = []
for ip in ip_list:
matched_ip = re.match(regex_exp, ip, re.MULTILINE|re.IGNORECASE|re.DOTALL)
if matched_ip:
print(matched_ip)
new_sanitized_list.append(ip)
else:
print("BAD IP: {}".format(ip))
print(new_sanitized_list)
return new_sanitized_list
Output:
>>> ip_list = ['10.0.0.1', '192.168.1.1', 'bob']
>>> verify_ip_is_ip(ip_list)
<_sre.SRE_Match object; span=(0, 8), match='10.0.0.1'>
<_sre.SRE_Match object; span=(0, 11), match='192.168.1.1'>
BAD IP: bob
['10.0.0.1', '192.168.1.1']
['10.0.0.1', '192.168.1.1']
>>>
My blog posts tagged with "Python Patterns" are designed to be a quick look reference for some Python code snippets I use a lot. They are written to be a quick starting point for future projects so I do not need to type as much.