我使用此模式检查字段的表单是否为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})?))$/;

当然,您可以进一步消除模式中的重复,但这会使从您提供的内容到开始的演变变得更加模糊:从更冗长,重复的模式开始;进行可靠的正面和负面测试;然后根据需要/期望进行重构以消除重复。

关于javascript - 带八位字节通配符和范围的IP地址,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31926178/

10-11 13:20