How to write an alphanumeric range checker in java which will check if the given alphanumeric value is within the range.
For example:
input: B3, range: B1:B10 - true
B1, B1:B10 - true
B10, B1:B10 - true
B1, B3:B10 - false
My attempt is failing for more than 1 digit numbers, example in B3:B10, the second prefix should be 'B' and num should be 10 but I get B1 and 0. Is there anything wrong with the regex?
public class Main {
public static final String RANGE_PATTERN = "(.+)(\\d)+:(.+)(\\d)+";
public static final String INPUT_PATTERN = "(.+)(\\d)+";
public static final Pattern P1 = Pattern.compile(RANGE_PATTERN);
public static final Pattern P2 = Pattern.compile(INPUT_PATTERN);
public static void main(String[] args) {
System.out.println(checkWithInRange("B3:B10", "B7"));
}
public static boolean checkWithInRange(String range, String input) {
Matcher m1 = P1.matcher(range);
Matcher m2 = P2.matcher(input);
if (m1.find() && m2.find()) {
String prefix1 = m1.group(1);
String num1 = m1.group(2);
String prefix2 = m1.group(3);
String num2 = m1.group(4);
String inputPrefix = m2.group(1);
String inputNum = m2.group(2);
if (prefix1.equalsIgnoreCase(prefix2) && prefix2.equalsIgnoreCase(inputPrefix)) {
int n1 = Integer.parseInt(num1);
int n2 = Integer.parseInt(num2);
int n3 = Integer.parseInt(inputNum);
if (n3 >= n1 && n3 <= n2) {
return true;
}
}
}
return false;
}
}
Use
"(.+?)...
to receive the shortest sequence (without digit). Or better yet"(\\D+)...
.Use
(\\d+)
instead of(\\d)+
so thatm.group(i)
is the entire string of digits.No need to use a null check on the groups, maybe you intended an optional prefix:
(\\D*)
.Did you intend
find()
or should it match the entire string:matches()
?