【问题标题】:IP addresses with octet wildcards and ranges带有八位字节通配符和范围的 IP 地址
【发布时间】:2015-11-02 18:11:56
【问题描述】:

我使用这个模式来检查一个字段的表单是否是一个 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

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

【问题讨论】:

  • 关于您的标签:设计模式和正则表达式模式彼此无关。不超过你衬衫上的图案。

标签: javascript html regex ip-address


【解决方案1】:

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

^(\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})?))$/;

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

【讨论】:

    【解决方案2】:

    这里至少有两个问题:

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

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

    【讨论】:

      猜你喜欢
      • 2014-10-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-13
      • 2020-10-17
      • 1970-01-01
      • 2018-10-04
      • 2011-02-11
      • 1970-01-01
      相关资源
      最近更新 更多