[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("BAD IP: {}".format(ip))
    return new_sanitized_list


>>> ip_list = ['', '', 'bob']
>>> verify_ip_is_ip(ip_list)
<_sre.SRE_Match object; span=(0, 8), match=''>
<_sre.SRE_Match object; span=(0, 11), match=''>
BAD IP: bob
['', '']
['', '']

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.