我想检查IP地址是否介于172.16.0.0和172.31.255.255
之间我试过的是:
Pattern address = Pattern.compile("172.[16-31].[0-255].[0-255]");
但它不起作用,编译器抛出错误:
Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal character range near index 8
172.[16-31].[0-255].[0-255]
^
由于这是一项练习,因此必须使用正则表达式。
答案 0 :(得分:3)
此处的一个选项是在期间拆分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;
}
}
答案 1 :(得分:3)
你的正则表达式不起作用的原因是字符组[16-31]
表示
“字符
1
,6
和3
之间的任何字符,或字符1
”
这绝对不是你想描述的。处理正则表达式语言中的数字很困难 - 例如,16到31是(1[6-9]|2\d|3[01])
,即“1
后跟6
到9
,2
后跟任何数字,或3
后跟0
或1
“。您需要使用类似的表达式来描述0..255
范围内的数字:(25[0-5]|2[0-4]\d|[01]?\d\d?)
。
更好的方法是使用InetAddress
,它具有getByName
方法来解析地址,并允许您使用getAddress()
方法检查地址的字节:
byte[] raw = InetAddress.getByName(ipAddrString).getAddress();
boolean valid = raw[0]==172 && raw[1] >= 16 && raw[1] <= 31;