const regex = /^(?:(?>([a-f0-9]{1,4})(?>:(?1)){7}|(?!(?:.*[a-f0-9](?>:|$)){8,})((?1)(?>:(?1)){0,6})?::(?2)?)|(?>(?>(?1)(?>:(?1)){5}:|(?!(?:.*[a-f0-9]:){6,})(?3)?::(?>((?1)(?>:(?1)){0,4}):)?)?(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\.(?4)){3}))$/img;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('^(?:(?>([a-f0-9]{1,4})(?>:(?1)){7}|(?!(?:.*[a-f0-9](?>:|$)){8,})((?1)(?>:(?1)){0,6})?::(?2)?)|(?>(?>(?1)(?>:(?1)){5}:|(?!(?:.*[a-f0-9]:){6,})(?3)?::(?>((?1)(?>:(?1)){0,4}):)?)?(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\\.(?4)){3}))$', 'img')
const str = `/*These should be valid*/
{Initial address}
2001:0db8:0000:0000:0000:ff00:0042:8329
{After removing all leading zeroes}
2001:db8:0:0:0:ff00:42:8329
{After omitting consecutive sections of zeroes}
2001:db8::ff00:42:8329
{The loopback address}
0000:0000:0000:0000:0000:0000:0000:0001
{The loopback address be abbreviated to ::1 by using both rules}
::1
{4 other valid test cases}
::FFFF:129.144.52.38
::129.144.52.38
::FFFF:d
1080:0:0:0:8:800:200C:417A
/*These 4 should be invalid*/
::FFFF:d.d.d
::FFFF:d.d
::d.d.d
::d.d`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions