CodexBloom - Programming Q&A Platform

Regex Not Capturing IP Address Ranges Properly in Python - Need guide with Edge Cases

👀 Views: 51 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-08
regex python ip-address Python

I'm experimenting with Hey everyone, I'm running into an issue that's driving me crazy..... I've searched everywhere and can't find a clear answer. I'm working on a Python application that needs to validate and capture IP address ranges in CIDR notation. However, I'm running into issues with my regex pattern not capturing certain valid ranges, particularly when it comes to subnet masks. My current regex pattern looks like this: ```python import re pattern = r'^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/(\d{1,2})$' ``` This pattern seems to work for most cases, but I noticed that when I test with the input `192.168.1.0/24`, it captures correctly, but for `10.0.0.0/8`, it fails to capture the subnet size correctly. The unexpected behavior is that it seems to allow values greater than 255 for the octets. I've tried adjusting the regex to restrict each octet to a valid range, but I still face issues. Here's an example of how I'm testing this: ```python test_ips = ['192.168.1.1/24', '10.0.0.0/8', '256.100.50.25/16'] for ip in test_ips: match = re.match(pattern, ip) if match: print(f'Matched: {match.group()}') else: print(f'No match for: {ip}') ``` The output is not as expected, especially with the third test case, which is clearly invalid, but my regex doesn't unexpected result it. How can I update my regex to ensure it correctly captures only valid IP ranges and restricts octet values appropriately? Any guidance on improving the regex to handle these edge cases would be greatly appreciated! My development environment is macOS. Any ideas what could be causing this? For context: I'm using Python on Ubuntu. What am I doing wrong?