Before everything,
- I have gone through several other regex related questions and also successfully came up with a solution but it looks like there might be a simpler solution
- I am a beginner with regex
- I am using java to execute this server side
Version should be of the format "< major >.< minor >.< beta >" with either of them having a range <0-999>
My desired behaviour is as follows
0 - 0.0.0
1 - 1.0.0
000.0.0 - 0.0.0
..9 - 0.0.9
00007 - 7.0.0
090876 - validate as false
9.00098000.00 - validate as false
9.0900000.00 - 9.09.0
-13.0.4 - validate as false
1a.0.4b - validate as false
My solution is as follows
if (StringUtils.isBlank(version)) {
//set error
} else {
if (!this.version.trim().matches("\\d+") && !(this.version.trim().matches("^-+"))
&& !(this.version.trim().matches("^+"))) {
String[] versionsplit = this.version.split("\\.");
// in the format <major>.<minor>.<beta> for major version, only
// leading zeroes should be removed
versionsplit[0] = versionsplit[0].trim().replaceFirst("^0+(?!$)", "");
if (versionsplit[0].length() == 0) {
// if major version is left blank add 0
versionsplit[0] = "0";
}
for (int i = 1; i < versionsplit.length; i++) {
// for minor and beta versions, trailing zeroes should be
// removed
versionsplit[i] = versionsplit[i].trim().replaceAll("0*$", "");
if (versionsplit[i].length() == 0) {
versionsplit[i] = "0";
}
}
this.version = StringUtils.join(versionsplit, ".");
if (versionsplit.length < 3) {
// to comply with the standard format <major>.<minor>.<beta>
for (int i = versionsplit.length; i < 3; i++) {
version += ".0";
}
}
} else {
//set error
}
if(< no error check > && !(version.matches("\\d(\\d(\\d)?)?(\\.\\d(\\d(\\d)?)?(\\.\\d(\\d(\\d)?)?)?)?"))) {
// set error
}
}
Tell me if this isn't the most complicated solution, i will be glad to let it be. I just want the code to be readable for the next person.
Please ask if requirement is unclear. Also please don't be frustrated if i do not respond immediately as i am not always online
Thanks in advance.
Edit
I understand the format checker at the end is more accurate in the below way.
if(< no error check > && !(version.matches("(?:[0-9]{1,3}\\.){2}[0-9]{1,3}$"))) {
// set error
}