CIDR Notation (IPv4) Regex for Python
/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\/(?:[0-9]|[12][0-9]|3[0-2])$/What this pattern does
This page provides a comprehensive, battle-tested regular expression for matching cidr notation (ipv4), ported and verified for Python. In security-sensitive code, using an unverified regex can open the door to both false positives and denial-of-service attacks. The snippet below is ready to drop into your Python project — whether you're validating in a Django view, a FastAPI endpoint, or a standalone data processing script.
Python Implementation
# CIDR Notation (IPv4)
# ReDoS-safe | RegexVault — Security > Network Security
import re
cidr_notation_ipv4_pattern = re.compile(r'^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\/(?:[0-9]|[12][0-9]|3[0-2])$')
def validate_cidr_notation_ipv4(value: str) -> bool:
return bool(cidr_notation_ipv4_pattern.fullmatch(value))
# Example
print(validate_cidr_notation_ipv4("192.168.1.0/24")) # TrueTest Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
192.168.1.0/24 | 192.168.1.0/33 |
10.0.0.0/8 | 192.168.1.0/-1 |
172.16.0.0/12 | 192.168.1.0 |
0.0.0.0/0 | 256.0.0.0/8 |
1.2.3.4/32 | 192.168.1.0/24/extra |
When to use this pattern
This pattern is drawn from the Security > Network Security category and carries a ReDoS-safe certification. That matters for Python developers because particularly important in Python web servers where CPU-bound regex operations can stall concurrent request handling. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.
Common Pitfalls
0.0.0.0/0 (any IP) in a security group rule exposes a service to the entire internet. 0.0.0.0/0 in outbound rules allows all outbound traffic. Review CIDR rules regularly in cloud security groups.
Technical Notes
/0 = all IPs (default route), /32 = single host. Subnets should have a host part of all zeros for canonical CIDR notation (192.168.1.0/24, not 192.168.1.5/24). Common in firewall rules, security groups, and IP allowlists.
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