Regex for Matching an IPv4 Address With CIDR Notation
Matches an IPv4 address followed by a slash and a prefix length, like 192.168.1.0/24.
Published October 13, 2026
This regex matches an IPv4 address followed by a /0–32 prefix length.
How the pattern works
Breaking the pattern down: IPv4 part = four octets 0–255; / = slash; (3[0-2]|[12]?\d) = prefix 0–32.
Test your regex against both matching and non-matching inputs; use the Regex tool on this site to experiment live.
Pattern tests
/^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)/(3[0-2]|[12]?\d)$/
✓ '192.168.0.0/24'
✓ '10.0.0.1/8'
✗ '192.168.0.0/33'
✗ '192.168.0.0'
Practical examples
The pattern
const re = /^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)/(3[0-2]|[12]?\d)$/Test it
const re = /^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)/(3[0-2]|[12]?\d)$/
re.test('192.168.0.0/24') // true
re.test('10.0.0.1/8') // true
re.test('192.168.0.0/33') // false
re.test('192.168.0.0') // falseIn Python
import re
re.search(r'^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)/(3[0-2]|[12]?\d)$', text)Common mistakes
- Not checking the prefix range.
- Host bits set in a network address.
- IPv6 CIDR needs another pattern.
Key takeaways
- Anchors (^ and $) make the whole string match instead of a part of it.
- Regex checks format only; verify data separately when it matters.
- Test with valid and invalid samples.
FAQ
Calculate ranges?
Use the CIDR Calculator on this site.
Where can I test this pattern?
Use the Regex Tester on this site, or regex101.com.