I want to make a regular expression that can help me get rid of the following piece of code -
public class Test {
public static void main(String[] args) {
String test = "1026";
int testToInt = 0;
if(checkIfInteger(test))
testToInt = Integer.parseInt(test);
if(testToInt >= 1024 && testToInt <= 65535)
System.out.println("Validity is perfect");
else
System.out.println("Validity is WRONG");
}
public static boolean checkIfInteger(String givenString) {
boolean check = false;
for(int i = 0; i < givenString.length(); i++) {
if(givenString.charAt(i) >= '0' && givenString.charAt(i) >= '9')
check = true;
else {
check = false;
break;
}
}
return check;
}
}
Basically, it is checking if a String contains only numeric digits and also that its range is between 1024 to 65535.
For this purpose, I created the following regex -
"\b(102[4-9]|10[3-9][0-9]|1[1-9][0-9]{2}|[2-9][0-9]{3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[01][0-9]|6552[0-5])\b"
But there's a lot of values for which it fails. Can someone give me a smarter / correct way to do it?
Here's a test file if you would want to test your regex -
public class Test {
public static void main(String[] args) {
for (int i = 0; i < 1024; i++) {
if (String
.valueOf(i)
.matches(
"\b(102[4-9]|10[3-9][0-9]|1[1-9][0-9]{2}|[2-9][0-9]{3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[01][0-9]|6552[0-5])\b"))
System.out.println("Hum " + i);
}
for (int i = 1025; i < (int) Math.pow(2, 16); i++) {
if (!String
.valueOf(i)
.matches(
"\b(102[4-9]|10[3-9][0-9]|1[1-9][0-9]{2}|[2-9][0-9]{3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[01][0-9]|6552[0-5])\b"))
System.out.println("Hum " + i);
}
for (int i = 0; i < 100; i++) {
if (String
.valueOf((int)Math.pow(2, 16) + i)
.matches(
"\b(102[4-9]|10[3-9][0-9]|1[1-9][0-9]{2}|[2-9][0-9]{3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[01][0-9]|6552[0-5])\b"))
System.out.println("Hum " + i);
}
}
}