Skip to content Skip to sidebar Skip to footer

Regex To Find If A Number Is Within A Range, Example 1,3,10-15,17

I would need to find a way How to check if a given number is included in a string of numbers and ranges. Here is an example: The string containing the numbers and ranges is '1,3,10

Solution 1:

The only way is to translate the range into a pattern (obviously), for that you need to forget that you are dealing with integers but only see digits as "normal characters". For your example range:

^(?:1[0-57]?|3)$

Note: regex is obviously not the way to check if an integer is in a numeric range. In real life, you will use good old conditionals.

Solution 2:

This isn't possible to do with just a regex. What you can do is use a regex (though in this case that's overkill) to extract the numbers, separating them into two classes: numbers and ranges. Then you can use this to determine if a number is in the list.

Post a Comment for "Regex To Find If A Number Is Within A Range, Example 1,3,10-15,17"