带八位字节通配符和范围的 IP 地址

IP addresses with octet wildcards and ranges

我用这个模式来检查字段的形式是否是 IP 地址:

function verifyIP (IPvalue) {
    errorString = "";
    theName = "IPaddress";

    var ipPattern = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
    var ipArray = IPvalue.match(ipPattern);

    if (IPvalue == "0.0.0.0") {
        errorString = errorString + theName + ': '+IPvalue+' is a special IP address and cannot be used here.';
    } else if (IPvalue == "255.255.255.255") {
        errorString = errorString + theName + ': '+IPvalue+' is a special IP address and cannot be used here.';
    } if (ipArray == null) {
        errorString = errorString + theName + ': '+IPvalue+' is not a valid IP address.';
    } else {
        for (i = 0; i < 4; i++) {
            thisSegment = ipArray[i];
            if (thisSegment > 255) {
                errorString = errorString + theName + ': '+IPvalue+' is not a valid IP address.';
                i = 4;
            }

            if ((i == 0) && (thisSegment > 255)) {
                errorString = errorString + theName + ': '+IPvalue+' is a special IP address and cannot be used here.';
                i = 4;
            }

            if (thisSegment.toString() == "*")
                errorString = "";
            }
        }

        extensionLength = 3;
        if (errorString == "")
            alert ("That is a valid IP address.");
        else
            alert (errorString);
    }
}

但我需要考虑具有带星号“*”或范围“0-255”的八位字节的字段的值。

例如:

192.168.1.1 --> It will be OK
192.168.*.* --> It will be OK
192.168.2-3.0-128 --> It will be OK
192.168.2-3.* --> It will be OK

有什么想法吗?非常感谢!

对于您提供的特定输入字符串,请从以下内容开始:

^(\d{1,3})\.(\d{1,3})\.(\*|(?:\d{1,3}(?:-\d{1,3})?))\.(\*|(?:\d{1,3}(?:-\d{1,3})?))$

Debuggex Demo

在您的 JavaScript 中,这将变为:

var ipPattern = /^(\d{1,3})\.(\d{1,3})\.(\*|(?:\d{1,3}(?:-\d{1,3})?))\.(\*|(?:\d{1,3}(?:-\d{1,3})?))$/;

当然,您可以进一步消除模式中的重复,但这将使从您提供的内容开始的演变更加不清晰:从更冗长、重复的模式开始;进行可靠的正面和负面测试;然后重构以消除重复 needed/desired.

这里至少有两个问题:

  1. 您的正则表达式应与允许位置的星号匹配。请参阅 J0e3gan 的回答中的正则表达式。

  2. 您正在遍历 match 返回的数组的索引 0-3。 match returns 索引 0 中的完整字符串和以下索引中的每个段。因此,您的 for 循环应如下所示:for (i = 1; i <= 4; i++) { // processing }.