I'm still a beginner at regex so this is a little above me currently.
I need to validate a number input to two characters and it can't be more than the value 12.
The two numbers easy:
/^\d{1,2}$/
Then check that if there are two numbers then the first must be either 0 or 1, and the second must be either 0, 1, or 2. That part I don't know how to express, regularly...
And also if possible I would like to have it in single regex statement.
Any help appreciated.
The [0-9] expression is used to find any character between the brackets. The digits inside the brackets can be any numbers or span of numbers from 0 to 9. Tip: Use the [^0-9] expression to find any character that is NOT a digit.
?= is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured. Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).
Example: Regex Number Range 1-20 Range 1-20 has both single digit numbers (1-9) and two digit numbers (10-20). For double digit numbers we have to split the group in two 10-19 (or in regex: "1[0-9]") and 20. Then we can join all these with an alternation operator to get "([1-9]|1[0-9]|20)".
Since regular expressions work with text, a regular expression engine treats 0 as a single character, and 255 as three characters. To match all characters from 0 to 255, we'll need a regex that matches between one and three characters. The regex [0-9] matches single-digit numbers 0 to 9.
Regex is not suited to dealing with ranges like this, but anyway this should work:
/^(0?[1-9]|1[012])$/
Description:
^ match start of the string
(0? optional zero
[1-9] any number between 1 and 9
|1[012]) or match 1 followed by either a 0, 1, 2 i.e. 10, 11, 12.
$ match end of string
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With