RRegexBuilder
Get RegexBuilder

RegexBuilder · regex answers

Regex for an IPv6 address

/^(([0-9a-f]{1,4}:){7}[0-9a-f]{1,4}|([0-9a-f]{1,4}:){1,7}:|:(:[0-9a-f]{1,4}){1,7}|::)$/i

IPv6 allows one run of zero groups to be replaced by ::, and that single rule is why a complete pattern is enormous. This covers the full eight-group form and the common compressed shapes. For production, use your platform's address parser — inet_pton exists everywhere.

What each part does

([0-9a-f]{1,4}:){7}seven groups with colons, then the eighth
([0-9a-f]{1,4}:){1,7}:compression at the end
:(:[0-9a-f]{1,4}){1,7}compression at the start
::the all-zeros address

Tested against real input

Every row below was run through the engine when this page was built. The third column is the substring the pattern actually matched.

InputResultMatched
2001:0db8:85a3:0000:0000:8a2e:0370:7334matches2001:0db8:85a3:0000:0000:8a2e:0370:7334
2001:db8::matches2001:db8::
::1matches::1
::matches::
2001:db8:::1no match
12345::no match
192.168.0.1no match

The mistake to avoid

Trying to cover every legal form, including embedded IPv4 like ::ffff:192.0.2.1, in one expression. The result is unmaintainable and still incomplete.

Try it on your own text

Paste this pattern and your input, see each match highlighted with its capture groups, step through what the engine did, and get the equivalent syntax for JavaScript, Python, Java, Go and PCRE.

Open RegexBuilder

Other regex answers