I am using below regular expression pattern
pattern=\"^(\\d|[1-9]\\d|1\\d\\d|2([0-4]\\d|5[0-5]))\\.(\\d|[1-9]\\d|1\\d\\d|2([0-4]\\d|5[0-5]))\\.(\\d|[1-9]\\d
I´d rather not use regex as @biziclop did say.
You could just split the whole String
and pass the ip adress to the InetAddress.html#getByName method. from the documentation of the method:
If a literal IP address is supplied, only the validity of the address format is checked
Basicly you could just pass the adress to this method, and the class itself would supply a validation of the adress. If the addres would be invalid you would run into a java.net.UnknownHostException
which you would just have to catch. This way you would just have to create a regex that will successfully split all the ip-adresses
public static void main(String[] args) throws UnknownHostException {
String adresses = "1.1.2.3.15,192.122.134.1,198.23.45.56";
for(String s : adresses.split(",|\\sor\\s")) {
try {
InetAddress adress = Inet4Address.getByName(s);
} catch (UnknownHostException e) {
System.out.println("Invalid format for ip adress " + s);
}
}
adresses = "1.1.2.3 or 192.122.134.1 or 198.23.45.56 ";
for(String s : adresses.split(",|\\sor\\s")) {
try {
InetAddress adress = Inet4Address.getByName(s);
} catch (UnknownHostException e) {
System.out.println("Invalid format for ip adress " + s);
}
}
}
output:
Invalid format for ip adress 1.1.2.3.15