My input number is an int. But the input number must be in a range from -2055 to 2055 and I want to check this by using regular expression.
So is there anyway to wri
Try with a very simple regex.
^([-0][0-1][0-9][0-9][0-9])$|^([-0]20[0-4][0-9])$|^([-0]205[0-5])$
Visual representation
It's very simple to understand.
[-0][0-1][0-9][0-9][0-9]
will cover [-1999, 1999] values[-0]20[0-4][0-9]
will cover [-2000,-2049] and [2000,2049] values[-0]205[0-5]
will cover [-2050, -2055] and [2050, 2055] values
String.format("%05d", number)
is doing very well done job here?
Sample code: (Read inline comments for more clarity.)
int[] numbers = new int[] { -10002, -3000, -2056, -2055, -2000, -1999, -20,
-1, 0, 1, 260, 1999, 2000, 2046, 2055, 2056, 2955,
3000, 10002, 123456 };
//valid range -2055 to 2055 inclusive
Pattern p = Pattern.compile("^([-0][0-1][0-9][0-9][0-9])$|^([-0]20[0-4][0-9])$|^([-0]205[0-5])$");
for (int number : numbers) {
String string = String.format("%05d", number);
Matcher m = p.matcher(string);
if (m.find()) {
System.out.println(number + " is in range.");
} else {
System.out.println(number + " is not in range.");
}
}
output:
-10002 is not in range.
-3000 is not in range.
-2056 is not in range.
-2055 is in range.
-2000 is in range.
-1999 is in range.
-20 is in range.
-1 is in range.
0 is in range.
1 is in range.
260 is in range.
1999 is in range.
2000 is in range.
2046 is in range.
2055 is in range.
2056 is not in range.
2955 is not in range.
3000 is not in range.
10002 is not in range.
123456 is not in range.