Write a regular expression that matches lines that only cont
Write a regular expression that matches lines that only contain a number between 20 and 29 (inclusive).
Solution
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.math.NumberUtils;
public class UserInputNumInRangeWRegex {
public static final void main(String[] ignored) {
int num = 20;
boolean isNum = false;
int iRangeMax = 29;
//\"\": Dummy string, to reuse matcher
/** Regular expression between numericals 20 and 29 **/
Matcher mtchrNumNegThrPos = Pattern.compile(\\b(?:20|29)\\b\").matcher(\"\");
do {
System.out.print(\"Enter a number between \" + num + \" and \" iRangeMax + \": \");
String strInput = (new Scanner(System.in)).next();
if(!NumberUtils.isNumber(strInput)) {
System.out.println(\"Not a number. Try again.\");
}
else if(!mtchrNumNegThrPos.reset(strInput).matches()) {
System.out.println(\"Not in range. Try again.\");
}
else {
//Safe to convert
num = Integer.parseInt(strInput);
isNum = true;
}while(!isNum);
System.out.println(\"Number: \" + num);
}
}
Output:
Enter a number between 20 and 29: tuhet
 Not a number. Try again.
 Enter a number between 20 and 29: 283837483
 Not in range. Try again.
 Enter a number between 20 and 29: -200000
 Not in range. Try again.
 Enter a number between 20 and 29: 27
 Number: 27


