REGEXVAULT
Web & Network/IPv4
ReDoS Checked

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])$/

All five implementations are free. Switch engines without signing in.

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

Python
# IPv4 with CIDR Notation
# ReDoS-checked | 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"))  # True

Test Cases

Matches (Valid)
Rejects (Invalid)
192.168.0.0/24192.168.1.1/33
10.0.0.0/8256.0.0.0/24
0.0.0.0/0192.168.1/24
255.255.255.255/32192.168.0.0/
172.16.0.0/12192.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-checked IPv4 CIDR pattern, you can confidently integrate it into your Flask or Django project — then check it against your own inputs before it handles untrusted traffic.

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. Submissions join the review queue after automated validation.

Submit a Pattern