CodexBloom - Programming Q&A Platform

Regex Not Matching IPv4 Addresses in Python - implementing Leading Zeros

👀 Views: 4784 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-09
regex python ipv4 Python

Hey everyone, I'm running into an issue that's driving me crazy. I'm trying to validate IPv4 addresses in Python using regex, but I'm having trouble with addresses that contain leading zeros. My current regex pattern is as follows: ```python import re ip_pattern = r'^(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]?)$' valid_ips = ['192.168.1.1', '255.255.255.255', '01.0.1.1', '192.168.01.1'] for ip in valid_ips: if re.match(ip_pattern, ip): print(f'{ip} is valid') else: print(f'{ip} is invalid') ``` When I run this code, I get the following output: ``` 192.168.1.1 is valid 255.255.255.255 is valid 01.0.1.1 is invalid 192.168.01.1 is invalid ``` The scenario seems to be with IPs that have leading zeros (like `01.0.1.1`), which I want to consider invalid. However, `192.168.01.1` should also be invalid due to the leading zero in the third octet, but it's currently being mismatched. I need a regex pattern that correctly identifies valid IPv4 addresses while rejecting those with leading zeros in any octet. How can I adjust my regex pattern to achieve this?