如何结合使用正则表达式和代码来验证 IPv6 地址?

Gil*_*ili 5 javascript regex

我想使用强调可读性的算法来验证 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;
}
Run Code Online (Sandbox Code Playgroud)

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

Gil*_*ili 5

这是布兰登答案的一个变体:

/**
 * @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'));
Run Code Online (Sandbox Code Playgroud)