What Is a Good Regex for IPv6 Address Validation?
Pattern: ^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$. An IPv6 address consists of eight groups of four hexadecimal digits separated by colons. The full form is 128 bits written as 8 groups. This basic regex validates the full expanded form; the :: shorthand notation requires a significantly more complex pattern or a dedicated library.
Breaking Down the Pattern
| Part | Meaning |
|---|---|
^ | Start of string |
[0-9a-fA-F]{1,4} | Match 1-4 hex characters (one group) |
: | Literal colon separator |
{7} | Repeat group:colon 7 times |
[0-9a-fA-F]{1,4}$ | Final group (1-4 hex chars), end of string |
Test Cases
| Input | Match? | Note |
|---|---|---|
2001:0db8:85a3:0000:0000:8a2e:0370:7334 | Yes | Valid format |
fe80:0000:0000:0000:0000:0000:0000:0001 | Yes | Valid format |
0000:0000:0000:0000:0000:0000:0000:0001 | Yes | Valid format |
2001:db8::1 | No | Uses :: shorthand (not matched by this basic pattern) |
192.168.1.1 | No | IPv4, not IPv6 |
Usage Examples
JavaScript
const pattern = /^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/;
pattern.test('2001:0db8:85a3:0000:0000:8a2e:0370:7334'); // true
pattern.test('2001:db8::1'); // false
Python
import re
pattern = r'^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$'
bool(re.match(pattern, '2001:0db8:85a3:0000:0000:8a2e:0370:7334')) # True
bool(re.match(pattern, '2001:db8::1')) # False
Common Pitfalls
- This basic pattern does not handle :: (zero compression) shorthand. A full IPv6 regex is extremely complex.
- IPv6 addresses are case-insensitive -- the pattern already handles this with a-fA-F.
- Some IPv6 addresses embed IPv4 (e.g., ::ffff:192.168.1.1) which requires additional patterns.
- For production, use a library (Python ipaddress, Node.js net.isIPv6) instead of regex.
Try It Yourself
Test this regex with our Regex Tester.
Frequently Asked Questions
Why is IPv6 regex so complex?
IPv6 allows zero compression (::) which can appear once in an address to replace consecutive groups of zeros. Handling all valid combinations of where :: can appear makes the regex extremely long.
What does :: mean in IPv6?
The :: notation replaces one or more consecutive groups of zeros. For example, 2001:db8::1 is shorthand for 2001:0db8:0000:0000:0000:0000:0000:0001.
Should I use regex to validate IPv6 in production?
No. Use a dedicated library. Python has ipaddress.ip_address(), Node.js has net.isIPv6(), and most languages have built-in or standard library support for IP validation.