Python Practice › RegEx Programs › Program 16
Validate an IPv4 address
Write a Python program to check IPv4 addresses (each part 0-255).
Output
192.168.1.10 True 256.1.1.1 False 10.0.0 False 8.8.8.8 True
Approach
- Use regex for the shape and Python for the range.
Solution
import re def is_ipv4(text): if not re.fullmatch(r"\d{1,3}(\.\d{1,3}){3}", text): return False return all(0 <= int(part) <= 255 for part in text.split(".")) for ip in ["192.168.1.10", "256.1.1.1", "10.0.0", "8.8.8.8"]: print(ip, is_ipv4(ip))Output
192.168.1.10 True 256.1.1.1 False 10.0.0 False 8.8.8.8 True
Line by line
Lines 4-6
A regex for 0-255 is long and hard to read; checking the numbers in Python is clearer.
Learn the concept
New to this topic? Read the lesson, then come back.