I think the proper way is to build an IPAddress
class and instanciate it by giving it a string representation of the the ip address.
This way you can split out the different validation steps into instance methods and get some separation of concern going.
For instance, this here is typically it's own method, call this simply isEmpty
:
return (ip == null || ip.isEmpty());
Also this should be a separate method, you could call this one hasProbableLength
.
ip = ip.trim();
return ((ip.length() < 6) & (ip.length() > 15));
Here there are lots of things going on. I would try to break this up and perhaps try to skip the regex completely.
try {
Pattern pattern = Pattern.compile("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");
Matcher matcher = pattern.matcher(ip);
return matcher.matches();
} catch (PatternSyntaxException ex) {
return false;
}
I would first split the string on dots and see that I get exactly four groups. Call this method divideIntoGroups
I would then validate each of the groups for being a value between 0 and 255. Call this method validateGroups
Now that you have this, if you ever want to extend this class to also look for if the IP is localhost or if it is a broadcast address, it is pretty easy to do this. This is what separation of concerns gives you.
You can also tell exactly which one of your validation rules was broken in the validation of the IP address string. Something that regex will not.