So I have a string specifying a valid range of numbers .
for eg.
String range = "100-200 , 500 , 1000-1200";
Need to check if a given integer value is within this specified range The range is different everytime.
You should first separate the different ranges. The valid ranges appear to be space-comma-space separated, so you need to split by ,.
String[] ranges = range.split(" , ");
And then for each range you need to split it by a hyphen. As Stultuske pointed out, you have to take into account the fact that the hyphen itself could be part of the integer notation. If you expect only positive values, then you can split by a single hyphen:
String rangeStr = "400-600";
String parts = rangeStr.split("-");
Alternatively, if you expect also negative values, then you should split by the first hyphen that is not at the start of the string, and apply the split only once.
String rangeStr = "-1200--1000";
// Splits by hyphen which is not preceded by the start of the string.
// The resulting array has no more than two elements
String[] parts = rangeStr.split("(?<!^)-", 2);
Note that this also works if a single value is given instead of a range, e.g. 500. Then, of course, parts.length is 1.
And then you can get the ints by calling Integer.valueOf(...).
Here is the code wrapped in a static method:
public static boolean inRange(String range, int value) {
return Arrays.stream(range.split(" , "))
.anyMatch(t -> {
// Split the two integers denoting the range. The length of the
// array is 1 if the range is an exact value (500 in your case),
// otherwise, its length is 2
String[] parts = t.split("(?<!^)-", 2);
int minVal = Integer.valueOf(parts[0]);
int maxVal = (parts.length == 2 ? Integer.valueOf(parts[1]) : minVal);
return (minVal <= value && value <= maxVal);
});
}
}
And here some tests:
String range = "-2100--2000, 100-200, 500, 1000-1200, 2000-2100";
System.out.println(inRange(range, -2150)); // false
System.out.println(inRange(range, -2000)); // true
System.out.println(inRange(range, 400)); // false
System.out.println(inRange(range, 500)); // true
System.out.println(inRange(range, 1100)); // true
Note that I have assumed that the source string is in the correct format. If you want to be a little more tolerant with what source string you expect (for example trailing spaces of multiple spaces in between), you have to implement that yourself.
-andInteger.parseIntthe numbers and check with>and<