简体   繁体   English

用于检查IP的正则表达式

[英]Regular expression to check IP

I want to check if an IP address is between 172.16.0.0 and 172.31.255.255 我想检查IP地址是否在172.16.0.0和172.31.255.255之间

What I tried is this: 我试过的是:

Pattern address = Pattern.compile("172.[16-31].[0-255].[0-255]");

But it doesn't work, the compiler throws an error: 但这不起作用,编译器将引发错误:

Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal character range near index 8
172.[16-31].[0-255].[0-255]
        ^

Since it's an exercise it has to be done with regular expressions. 由于这是一项练习,因此必须使用正则表达式来完成。

One option here would be to split the IP address on period and then check to make sure each component is within the ranges you want: 这里的一种选择是按期限分割IP地址,然后检查以确保每个组件都在所需范围内:

public boolean isIpValid(String input) {
    String[] parts = input.split("\\.");
    int c1 = Integer.parseInt(parts[0]);
    int c2 = Integer.parseInt(parts[1]);
    int c3 = Integer.parseInt(parts[2]);
    int c4 = Integer.parseInt(parts[3]);

    if (c1 == 172 &&
        c2 >= 16 && c2 <= 31 &&
        c3 >= 0 &&  c3 <= 255 &&
        c4 >= 0 &&  c4 <= 255) {
        System.out.println("IP address is valid.");
        return true;
    } else {
        System.out.println("IP address is not valid.");
        return false;
     }
}

The reason your regex does not work is that the character group [16-31] means 您的正则表达式不起作用的原因是字符组[16-31]表示

"character 1 , any character between 6 and 3 , or character 1 " “字符1之间的任何字符63 ,或字符1

This is definitely not what you wanted to describe. 这绝对不是您想要描述的。 Treating numbers in regex language is difficult - for instance, 16 through 31 is (1[6-9]|2\\d|3[01]) , ie " 1 followed by 6 through 9 , 2 followed by any digit, or 3 followed by 0 or 1 ". 在正则表达式语言处理的数字是难以-例如,16到31是(1[6-9]|2\\d|3[01])即,“ 1 ,接着6通过92后跟任何数字或3后跟01 ”。 You will need a similar expression to describe numbers in the 0..255 range: (25[0-5]|2[0-4]\\d|[01]?\\d\\d?) . 您将需要一个类似的表达式来描述0..255范围内的数字: (25[0-5]|2[0-4]\\d|[01]?\\d\\d?)

A lot better approach would be to use InetAddress , which has a getByName method for parsing the address, and lets you examine the bytes of the address with getAddress() method: 更好的方法是使用InetAddress ,它具有用于解析地址的getByName方法,并允许您使用getAddress()方法检查地址的字节:

byte[] raw = InetAddress.getByName(ipAddrString).getAddress();
boolean valid = raw[0]==172 && raw[1] >= 16 && raw[1] <= 31;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM