IPv4 with CIDR Notation Regex for Python
/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\/(?:3[0-2]|[12][0-9]|[0-9])$/What this pattern does
Need to validate IPv4 addresses with CIDR notation in your Python application? This robust regex efficiently parses and validates network addresses such as 192.168.1.0/24, ensuring both address correctness and the validity of the prefix length. This pattern can be invaluable for projects using Python's `re` module, where precise input validation is essential, such as in network configuration tools or security applications.
Python Implementation
# IPv4 with CIDR Notation
# ReDoS-safe | RegexVault — Web & Network > IPv4
import re
ipv4_with_cidr_notation_pattern = re.compile(r'^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\/(?:3[0-2]|[12][0-9]|[0-9])$')
def validate_ipv4_with_cidr_notation(value: str) -> bool:
return bool(ipv4_with_cidr_notation_pattern.fullmatch(value))
# Example
print(validate_ipv4_with_cidr_notation("192.168.0.0/24")) # TrueTest Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
192.168.0.0/24 | 192.168.1.1/33 |
10.0.0.0/8 | 256.0.0.0/24 |
0.0.0.0/0 | 192.168.1/24 |
255.255.255.255/32 | 192.168.0.0/ |
172.16.0.0/12 | 192.168.0.0 |
When to use this pattern
ReDoS vulnerabilities pose a significant threat to Python applications, particularly those exposed to untrusted input. An unsafe regex can allow a malicious actor to craft a specially designed input that consumes excessive CPU resources, leading to denial-of-service. With this ReDoS-safe IPv4 CIDR pattern, you can confidently integrate it into your Flask or Django project knowing it won't be exploited in a production environment.
Common Pitfalls
Using [0-9]{1,2} for the prefix allows /99. Always use the bounded alternation.
Technical Notes
Prefix length alternatives: 3[0-2] covers 30–32, [12][0-9] covers 10–29, [0-9] covers 0–9. Combined this gives 0–32 exactly.
Have a pattern that belongs in the vault?
Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.
Submit a Pattern