I need a regex for an integer starting from 25 with no limit I tried:
^([2-9]\d[0-9]\d{2,})$
but I need it to start from 25 not 20 and I'm not even sure if this works correctly.
I need a regex for an integer starting from 25 with no limit I tried:
^([2-9]\d[0-9]\d{2,})$
but I need it to start from 25 not 20 and I'm not even sure if this works correctly.
Your regex
^([2-9]\d[0-9]\d{2,})$
Will match any number starting with 2-9
and having 5 digits or more (\d
, [0-9]
contribute one digit each, \d{2,}
is for another two or more digits). You want something like this:
^0*(1\d\d|2[0-4]\d|2[5-9]|[3-9]\d)\d*$
As you can see this is rather ugly. If you are using some kind of programming languages, you should rather assert that it is a number (^\d*$
) and check the range without regex.
But how does my regex work?
First we consume leading 0
s because they don't change the value of the number. And then we have an alternation depending on the first digit(s) of the number. If it's a 1
we know we need at least two more digits for it to be greater than 25
. If it's a 2
and the second digit is between 0
and 4
we also need another digit. If it's 25
or starts with 3
to 9
, two digits suffice. And after the alternation, we just allow arbitrarily many more digits.
Test it here
^(2[5-9]([0-9])*|[3-9][0-9]+|[1-2][0-9]{2,})$
You can also use regex to check the complement of that: (Eliminate anything that doesn't qualify: i.e match any thing that is less than 25)
-
(negative)[0-2]
, and[0-4]
, and> 200
)Here is a regex that is slightly more concise than some of the others:
^(?!(1\d|2[0-4])$)[1-9]\d+$
You can test it here: http://www.rubular.com/r/PGdbtGYsWD
The approach is to just match [1-9]\d+
, which will be a two or more digit number, and use a negative lookahead at the beginning to prevent matches for any numbers between 10 and 24.
If leading zeros should be allowed, just add 0*
directly after the ^
.
Use regex pattern
^(2[5-9]|[3-9]\d|(?!0)\d{3,})$
or (if you want to allow leading zeros)
^0*(2[5-9]|[3-9]\d|(?!0)\d{3,})$