【问题标题】:IP address validation with wildcard character使用通配符验证 IP 地址
【发布时间】:2011-06-12 08:07:20
【问题描述】:
String ip = "1.1.&.&";
String WILDCARD_CHARACTER = "&";
String REGEX_IP_ADDRESS_STRING = "(?:(?:"
        + WILDCARD_CHARACTER
        + "|25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:"
        + WILDCARD_CHARACTER + "|25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
Pattern p = Pattern.compile(REGEX_IP_ADDRESS_STRING1);
Matcher m = p.matcher(ip);
System.out.println("Does it match? " + m.matches());

使用上述编码的 IP 验证非常有效。但我想对导致问题的通配符进行一些修改。

当前情景:

  • 192.1.&.& ------> 是的
  • 192.1.0.1 ------>是的
  • & ------> 错误
  • 192.1.& ------> 错误

预期:

  • 192.1.&.& ------> 错误
  • 192.1.0.1 ------>是的
  • & ------> 是的
  • 192.1.& ------> 是的

即我想在通配符之后对所有输入进行通配符。

正则表达式中的哪些修改可以帮助我实现这一目标?谁能帮帮忙?

【问题讨论】:

    标签: java regex validation


    【解决方案1】:

    我建议如下(我在这个正则表达式中使用了文字 &;当然你可以将其更改为 + WILDCARD_CHARACTER 构造):

    Pattern regex = Pattern.compile(
        "^       # Anchor the match at the start of the string\n" +
        "(?:     # Match either...\n" +
        " &      # the wildcard character\n" +
        " |      # or a number between 0 and 255\n" +
        " (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\n" +
        " \\.    # followed by a dot, followed by...\n" +
        " (?:    # ...either...\n" +
        "  &     # the wildcard character\n" +
        "  |     # or a number etc. etc.\n" +
        "  (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\n" +
        "  \\.\n" +
        "  (?:\n" +
        "   &\n" +
        "   |\n" +
        "   (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\n" +
        "   \\.\n" +
        "   (?:\n" +
        "    &\n" +
        "    |\n" +
        "    (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\n" +
        "   )\n" +
        "  )\n" +
        " )\n" +
        ")\n" +
        "$        # Anchor the match at the end of the string", 
        Pattern.COMMENTS);
    

    【讨论】:

      【解决方案2】:

      (?:2[0-4]\d|25[0-5]|1\d\d|\d\d|\d).(?:2[0-4]\d|25 [0-5]|1\d\d|\d\d|\d).(?:2[0-4]\d|25[0-5]|1\d\d|\d\d |\d).(?:2[0-4]\d|25[0-5]|1\d\d|\d\d|\d) |(?:2[0-4]\d|25[0-5]|1\d\d|\d\d|\d).(?:2[0-4]\d|25[0 -5]|1\d\d|\d\d|\d).(?:2[0-4]\d|25[0-5]|1\d\d|\d\d|\ d).& |(?:2[0-4]\d|25[0-5]|1\d\d|\d\d|\d).(?:2[0-4]\d|25[0 -5]|1\d\d|\d\d|\d).& |(?:2[0-4]\d|25[0-5]|1\d\d|\d\d|\d).& |&

      所有内容都应符合您的要求

      【讨论】:

        猜你喜欢
        • 2012-07-03
        • 1970-01-01
        • 2021-01-03
        • 2014-05-13
        • 2012-02-29
        • 1970-01-01
        • 1970-01-01
        • 2016-12-22
        • 1970-01-01
        相关资源
        最近更新 更多