0

有人可以帮助我使用正则表达式来匹配一系列 IP。它应该匹配如下内容:

"203.0.113.0-203.0.113.255"

我尝试了以下方法,但仅匹配单个 IP:

((?:\\d{1,3}\\.){3}\\d{1,3})(?:/((?:(?:\\d{1,3}\\. ){3}\\d{1,3})|\\d{1,2}))?
4

5 回答 5

2

您可以将字符串拆分为 2 个组件

String[] splitResult = ipRange.split("-");

然后对每个子字符串使用此模式

string pattern = @"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"

您的模式实际上不起作用,因为每个 IP 部分最多只能达到 255

于 2013-03-20T14:16:31.750 回答
0

如果您有匹配单个 IP 的正则表达式,那么只需添加-并重复您的正则表达式

String singleIPRegex = "yourRegex";
String rangeRegex = singleIPRegex + "-" + singleIPRegex;

if (someString.matches(rangeRegex)){
    //do your stuff
}

也可以作为 singleIPRegex 使用

(([01]?\\d{1,2}|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d{1,2}|2[0-4]\\d|25[0-5])

部分

([01]?\\d{1,2}|2[0-4]\\d|25[0-5])

将接受:

  • [01]?\\d{1,2}-> 范围 0-199,包括以 0 或 00 开头的数字,例如 01、001
  • 2[0-4]\\d-> 范围 200-249
  • 25[0-5]-> 范围 250-255
于 2013-03-20T14:18:47.100 回答
0

试试这个 :((?:\d{1,3}\.){3}\d{1,3})(?:/((?:(?:\d{1,3}\.){3}\d{1,3})|\d{1,2})){2}

于 2013-03-20T14:21:43.093 回答
0

试试这个:

String data = "This http://example.com is a sentence 203.0.113.0-203.0.113.255 https://secure.whatever.org that contains 2 URLs.";


    Pattern pattern = Pattern.compile("\\s((\\d{1,4}\\.?){4}-(\\d{1,4}\\.?){4})\\s");
    Matcher matcher = pattern.matcher(data);

    while (matcher.find()) {
        System.out.println(matcher.group(1));
    }

希望这可以帮助。

于 2013-03-20T16:32:01.780 回答
0

您可以在此页面https://www.analyticsmarket.com/freetools/ipregex/中为 IP 范围生成正则表达式

对于您的情况,生成的正则表达式^203\.0\.113\.([1-9]?\d|[12]\d\d)$适用于范围内的 IP 地址203.0.113.0 to 203.0.113.255

于 2021-11-12T07:32:05.893 回答