Regex for Validating IP Addresses in Python - Trouble with CIDR Notation
I'm converting an old project and I'm sure I'm missing something obvious here, but I'm trying to configure This might be a silly question, but I'm working on a Python application that needs to validate both regular IPv4 addresses and those expressed in CIDR notation (e.g., `192.168.1.0/24`)..... I've tried a few regex patterns, but I'm struggling to account for the CIDR part without making the regex overly complicated or inefficient. Hereβs the regex pattern I came up with for the regular IPv4 addresses: ```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]?)$' ``` This works perfectly for standalone IPs, but when I try to extend it to include the CIDR notation, I end up with either very complex regex or it fails to validate correctly. For example, the following input: ```python ip_input = '192.168.1.0/24' ``` doesn't match. I have attempted to add the CIDR part like this: ```python 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]?)\/([0-9]|[1-2][0-9]|3[0-2])$' ``` This seems to work for `192.168.1.0/24`, but fails when I test `10.0.0.1/8`. The behavior I get is `ValueError: too many values to unpack (expected 2)`. How can I effectively validate both standalone IP addresses and CIDR notation in a single regex pattern without running into these issues? Any tips on simplifying the regex would also be appreciated. I'm currently using Python 3.9.7. For context: I'm using Python on Linux. Am I missing something obvious? This is happening in both development and production on CentOS. Thanks, I really appreciate it! This is part of a larger desktop app I'm building. Am I approaching this the right way? Hoping someone can shed some light on this.