I need expression to check if number 7 is less than 30 and greater than 1. This is an example. Can anybody provide expression and an explanation?
Asked
Active
Viewed 3,100 times
1
-
4Regex is probably not the best way to approach this... – Joel May 13 '14 at 17:16
-
This is an example of much complex problem. I have other solution but i need to find one with regex. – opejanovic May 13 '14 at 17:19
-
Please describe the complex problem then - do the ranges change? Why regex? – Tim Pietzcker May 13 '14 at 17:22
-
Unlike forum sites, we don't use "Thanks", or "Any help appreciated", or signatures on [so]. See "[Should 'Hi', 'thanks,' taglines, and salutations be removed from posts?](http://meta.stackoverflow.com/questions/2950/should-hi-thanks-taglines-and-salutations-be-removed-from-posts). – John Saunders May 13 '14 at 17:29
2 Answers
1
^([2-9]|[1-2][0-9])$
The expression above will match, if:
- the given string is one character long and that character is a number ranging from 2 to 9
- the given string is two characters long, first character is 1 or 2 and the second character ranges from 0 to 9

Khub
- 113
- 1
- 11
0
Don't use regex, but if you want to, here you go:
^(?:[2-9]|[1-2][0-9])$
Explanation:
This anchors to the beginning/end of the string (so we don't match 7
in the number 175
) and then all of the logic happens in the non-capturing group. Either match the numbers [2-9 ]
(greater than 1) OR match [1-2]
followed by any digit [0-9]
(range from 10-29). Notice that I used [0-9]
instead of \d
because it fits better for readability and \d
technically will match other numeric characters (Arabic, etc).
Side note, if you want to allow leading 0's (1 < 007 == 7 < 30
), you can allow for 0+ 0's after the start of the string:
^0*(?:[2-9]|[1-2][0-9])$

Sam
- 20,096
- 2
- 45
- 71