gpt4 book ai didi

java - 使用通配符验证 IP 地址

转载 作者:搜寻专家 更新时间:2023-10-31 20:06:40 25 4
gpt4 key购买 nike

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.& ------> 正确

即我想在通配符后通配所有输入。

对正则表达式进行哪些修改可以帮助我实现这一目标?任何人都可以帮忙吗?

最佳答案

我建议如下(我在此正则表达式中使用了文字 &;当然您可以将其更改为您的 + 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);

关于java - 使用通配符验证 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4745418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com