oblac / jodd

Jodd! Lightweight. Java. Zero dependencies. Use what you like.

Home Page:https://jodd.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Simplifying validateAgaintIPAdressV4Format

neroux opened this issue · comments

Hi @igr, pardon my laziness :) this actually should be rather a pull request but, even though I am confident it will work, I havent extensively tested it (read "not at all in a Java context") and hence wouldnt want to officialise my laziness will a pull request, but rather "dump" it as an issue 🙄.

It should essentially simplify the code at

public static boolean validateAgaintIPAdressV4Format(final String input) {
if (input == null) {
return false;
}
int hitDots = 0;
char[] data = input.toCharArray();
for (int i = 0; i < data.length; i++) {
char c = data[i];
int b = 0;
do {
if (c < '0' || c > '9') {
return false;
}
b = (b * 10 + c) - 48;
if (++i >= data.length) {
break;
}
c = data[i];
} while (c != '.');
if (b > 255) {
return false;
}
hitDots++;
}
return hitDots == 4;
}

public static boolean validateIPv4(final String input) {
	return (input + '.').matches("^((?:1?[1-9]?\\d|2(?:[0-4]\\d|5[0-5]))\\.){4}$");
}

The reason why I am confident it should work is, that the expression itself looked fine during a preliminary test, due to the concatenated period there shouldnt be a null pointer either, and that period also simplifies the expression as we can have a {4} there.

It is a breaking change, as it renames the method, but I took that liberty as there was a typo in it anyhow and it now is a bit shorter.

Please really just take this as a suggestion, I have not benchmarked it, there is a chance it is slower than the existing version due to the use of the regex engine. Please also feel free to edit it at your discretion, and once again, please pardon my laziness :).

No worries @neurox! It works very nice. For the performance, I just split pattern compilation to static final field.