Reputation: 2310
I am trying to validate numbers which are allowed to belong to multiple ranges. e.g.:
A number x is valid if it lies between 150-200, or 700-750
Basically I want to store these restrictions in a database, so I thought storing them as regexes would be a nice way of handling this problem.
I am new to regular expressions, so am not being able to come up with one for the above validation.
Upvotes: 1
Views: 1842
Reputation: 569
Solution:
1[5-9][0-9]|200|7[0-4][0-9]|750
Explanation:
Since you have a very well defined ranges, the regex is fairly simple.
It can be broken up into two parts:
So, put together the regex will read as
((150 through 199 OR 200) OR (700 through 749 OR 750))
Your first number is 150, so we will have to match a '1' for the first digit followed by the range for the second digit which could be 5 though 9 (you don't want anything less that 150, so 4 and less are out) and also followed by the range for the third digit which could be anything from 0 to 9. This captures all numbers from 150 to 199.
The last number in the first range is 200, so we can just look for that. It is too different from the rest of the possibilities in the range, thus it is easier to look for specifically for it instead of trying to think of a complex way of including it in a regex range.
The second range follows the same patten but with different numbers. Again, we are looking for most of the numbers by using the regex range and looking for the last number, 750, specifically since it is too different -- has a number 5 in the middle. If we include 5 in the middle regex range, it will go up to 759, which is outside of the scope.
Finally, OR both parts and the regex is ready.
Adjust for your input. You may need to surround it with ^ and $ for the beginning and the end of the line or if your input has other text surrounding the number in question, expand your regex to deal with it appropriately.
Upvotes: 2