Tutorial :Regular Expression - Range (2-16)?



Question:

All i want to do is match a number between 2-16, spanning 1 digit to 2 digits

according to http://www.regular-expressions.info/numericranges.html, they have examples for 1 or 2 digit ranges, but not something that spans both..if that makes sense.

The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99.  

Something like "^[2-9][1-6]$" matches 21 or even 96 lol. Any help would be appreciated.


Solution:1

^([2-9]|1[0-6])$  

will match either a single digit between 2 and 9 inclusive, or a 1 followed by a digit between 0 and 6, inclusive.


Solution:2

With delimiters (out of habit): /^([2-9]|1[0-6])$/

The regex itself is just: ^([2-9]|1[0-6])$


Solution:3

^([2-9]|1[0-6])$  

(Edit: Removed quotes for clarification.)


Solution:4

(^[2-9]$|^1[0-6]$)

By specifying start and stop for each set of numbers you are looking for your regex won't also return 36, 46, ... and so on. I tried the above solution and found that this works best for staying within the range of 2-16.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Latest
Previous
Next Post »