gpt4 book ai didi

javascript - 如何结合使用 RegEx 和代码来验证 IPv6 地址?

转载 作者:行者123 更新时间:2023-11-29 10:06:59 25 4
gpt4 key购买 nike

我想使用强调可读性的算法来验证 IPv6 地址。理想的解决方案是将极其简单的正则表达式与源代码相结合。

使用 https://blogs.msdn.microsoft.com/oldnewthing/20060522-08/?p=31113举个例子:

function isDottedIPv4(s)
{
var match = s.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
return match != null &&
match[1] <= 255 && match[2] <= 255 &&
match[3] <= 255 && match[4] <= 255;
}

请注意 Raymond 如何将复杂性从正则表达式转移到代码中。我想要一个对 IPv6 执行相同操作的解决方案。

最佳答案

这是 Brandon's answer 的一个变体:

/**
* @param {String} a String
* @return {Boolean} true if the String is a valid IPv6 address; false otherwise
*/
function isIPv6(value)
{
// See https://blogs.msdn.microsoft.com/oldnewthing/20060522-08/?p=31113 and
// https://4sysops.com/archives/ipv6-tutorial-part-4-ipv6-address-syntax/
const components = value.split(":");
if (components.length < 2 || components.length > 8)
return false;
if (components[0] !== "" || components[1] !== "")
{
// Address does not begin with a zero compression ("::")
if (!components[0].match(/^[\da-f]{1,4}/i))
{
// Component must contain 1-4 hex characters
return false;
}
}

let numberOfZeroCompressions = 0;
for (let i = 1; i < components.length; ++i)
{
if (components[i] === "")
{
// We're inside a zero compression ("::")
++numberOfZeroCompressions;
if (numberOfZeroCompressions > 1)
{
// Zero compression can only occur once in an address
return false;
}
continue;
}
if (!components[i].match(/^[\da-f]{1,4}/i))
{
// Component must contain 1-4 hex characters
return false;
}
}
return true;
}


console.log('Expecting true...');
console.log(isIPv6('2001:cdba:0000:0000:0000:0000:3257:9652'));
console.log(isIPv6('2001:cdba:0:0:0:0:3257:9652'));
console.log(isIPv6('2001:cdba::3257:9652'));
console.log(isIPv6('2001:cdba::257:9652'));
console.log(isIPv6('2001:DB8:0:2F3B:2AA:FF:FE28:9C5A'));
console.log(isIPv6('::0:2F3B:2AA:FF:FE28:9C5A'));
console.log('\n');
console.log('Expecting false...');
console.log(isIPv6(':0:2F3B:2AA:FF:FE28:9C5A'));

关于javascript - 如何结合使用 RegEx 和代码来验证 IPv6 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41435985/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com