There's a couple problems with the other answer by @ClasG:
- If the repeating zeroes are at the beginning of the IPv6 address or it's all zeroes, only 1 colon is replaced.
- If the repeating zeroes are at the end, they're not replaced.
I suggest using the regex \b:?(?:0+:?){2,}
and have it replaced with ::
(two colons)
Regex101 tests
JavaScript example:
var ips = [
'2001:0db8:ac10:0000:0000:0000:0000:ffff',
'2001:0db8:ac10:0000:0000:0000:0000:0000',
'0:0:0:0:0:2001:0db8:ac10',
'2001:0db8:ac10:aaaa:0000:bbbb:cccc:ffff',
'2001:0db8:ac10:0000:0000:bbbb:00:00'
];
for (var i = 0; i < ips.length; i++) {
document.write(ips[i].replace(/\b:?(?:0+:?){2,}/, '::') + "<br>");
}
Note: The Regex101 tests replace multiple repeating groups of zeroes. In XYZ programming language, you'll have to limit the number of replacements to 1. In JavaScript, you omit the global flag. In PHP, you set the $limit
for preg_replace
to 1.