Regular expressions will be executed. There are simple and more complex ones. Simple is this regular expression:
\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}
Use it as follows:
boolean isIP = someIP.maches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
But it will also correspond to 999.999.999.999, which is not a valid IP address. There is a huge regex available at regular-expressions.info :
(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]?)
This person will take care of the job properly. If you use this, be sure to avoid each \ other \ .
If you are not a fan of huge regular expressions, you can use this code:
public static boolean isIP(String str) { try { String[] parts = str.split("\\."); if (parts.length != 4) return false; for (int i = 0; i < 4; ++i) { int p = Integer.parseInt(parts[i]); if (p > 255 || p < 0) return false; } return true; } catch (Exception e) { return false; } }
Martijn courteaux
source share