CIDR Notation (IPv6) Regex for Python
/^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\/(?:1[01][0-9]|12[0-8]|[0-9]{1,2})$|^::(?:[fF]{4}(?::0{1,4})?:)?(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})){3}\/(?:1[01][0-9]|12[0-8]|[0-9]{1,2})$|^(?:[0-9a-fA-F]{0,4}:){1,7}(?::[0-9a-fA-F]{0,4}){0,7}\/(?:1[01][0-9]|12[0-8]|[0-9]{1,2})$/iWhat this pattern does
This page provides a comprehensive, battle-tested regular expression for matching cidr notation (ipv6), 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 (IPv6)
# ReDoS-safe | RegexVault — Security > Network Security
import re
cidr_notation_ipv6_pattern = re.compile(r'^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\/(?:1[01][0-9]|12[0-8]|[0-9]{1,2})$|^::(?:[fF]{4}(?::0{1,4})?:)?(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})){3}\/(?:1[01][0-9]|12[0-8]|[0-9]{1,2})$|^(?:[0-9a-fA-F]{0,4}:){1,7}(?::[0-9a-fA-F]{0,4}){0,7}\/(?:1[01][0-9]|12[0-8]|[0-9]{1,2})$')
def validate_cidr_notation_ipv6(value: str) -> bool:
return bool(cidr_notation_ipv6_pattern.fullmatch(value))
# Example
print(validate_cidr_notation_ipv6("2001:db8::/32")) # TrueTest Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
2001:db8::/32 | 2001:db8::/129 |
::1/128 | 2001:db8:: |
fe80::/10 | ::1 |
::/0 | 192.168.0.0/24 |
2001:0db8:85a3:0000:0000:8a2e:0370:7334/64 | — |
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
IPv6 has multiple equivalent representations for the same address (:: compression, leading zero omission). Normalize to RFC 5952 canonical form before comparison or storage.
Technical Notes
IPv6 CIDR prefixes: /48 is common for ISP assignments, /64 for subnets (standard for SLAAC), /128 for single hosts. ::/0 is the IPv6 default route. fe80::/10 is link-local. ::1/128 is loopback.
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