← Back to all snippets
PYTHON

Validating IPv4 Addresses with Regular Expressions in Python

Learn to accurately validate IPv4 address formats using a robust regular expression in Python, ensuring correct network address inputs in your applications.

import re

def is_valid_ipv4(ip_address):
    # Regex for an IPv4 address, ensuring each octet is 0-255
    ipv4_regex = r"^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"
    return re.match(ipv4_regex, ip_address) is not None

print(is_valid_ipv4("192.168.1.1")) # True
print(is_valid_ipv4("10.0.0.255"))  # True
print(is_valid_ipv4("256.0.0.1"))  # False (256 is invalid)
print(is_valid_ipv4("192.168.1"))   # False (incomplete)
How it works: This Python function `is_valid_ipv4` employs a precise regular expression to validate if a string is a correctly formatted IPv4 address. The regex ensures that each of the four octets is a number between 0 and 255, and that they are separated by dots, making it suitable for input validation.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs