Regex for IPv6 Address Validation — Full and Compressed Forms
Regex for IPv6 address validation supporting full form, :: compression, and IPv4-mapped addresses. Includes link-local zones and CIDR notation.
Detailed Explanation
Regex for IPv6 Address Validation
IPv6 (RFC 4291) defines a 128-bit address as eight groups of four hex digits separated by colons. Multiple representations are valid: full form, leading-zero suppression, :: zero compression, IPv4-mapped form, and link-local with zone IDs. A single regex covering all of them is intentionally long.
Comprehensive Pattern
^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$
Form-by-Form Breakdown
| Form | Example |
|---|---|
| Full | 2001:0db8:85a3:0000:0000:8a2e:0370:7334 |
| Leading-zero suppressed | 2001:db8:85a3:0:0:8a2e:370:7334 |
:: compression |
2001:db8::8a2e:370:7334 |
| Loopback | ::1 |
| Unspecified | :: |
| IPv4-mapped | ::ffff:192.168.1.1 |
IPv4-Mapped Extension
To also match IPv4-mapped addresses, append this branch to the alternation:
::(ffff(:0{1,4})?:)?((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]?)
Tested Examples
| Input | Matches? |
|---|---|
::1 |
yes |
2001:db8::1 |
yes |
fe80::1 |
yes |
gggg::1 |
no (not hex) |
2001:db8:::1 |
no (triple colon) |
Notes
The :: may appear at most once. Zone IDs (e.g. fe80::1%eth0) and CIDR (/64) require additional optional groups. For anything beyond display formatting, use a real parser.
Use Case
Validating IPv6 addresses entered into network configuration forms, extracting addresses from dual-stack server logs, or auditing source code for hardcoded loopback addresses.