Reputation: 1233
I want to check if an IP address is between 172.16.0.0 and 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.
Upvotes: 0
Views: 125
Reputation: 726479
The reason your regex does not work is that the character group [16-31]
means
"character
1
, any character between6
and3
, or character1
"
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])
, i.e. "1
followed by 6
through 9
, 2
followed by any digit, or 3
followed by 0
or 1
". You will need a similar expression to describe numbers in the 0..255
range: (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:
byte[] raw = InetAddress.getByName(ipAddrString).getAddress();
boolean valid = raw[0]==172 && raw[1] >= 16 && raw[1] <= 31;
Upvotes: 3
Reputation: 520878
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:
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;
}
}
Upvotes: 3