I'm trying to build up some regular expressions to validate some textbox controls. I have done some research and testing but cannot get this one working. Examples of what i am trying to create regular expressions for are as follows:
For 1 and 5 respectively, I have used
([0-9]|[0-9]\d|45)$
([0-9]|[0-9]\d|1500000)$
The first one I am having problems for is an age range of 16-65 (inclusive), where I want no decimal places. After a post on here (Regular expression to allow numbers between -90.0 and +90.0) I thought I could use the logic and get it sussed, but can't!
The expression I got to was:
(\d|([1-6][6-4]))|65
Can someone please tell me where I'm misunderstanding this! And any help with the other examples above would be gratefuly received.
Sorry to say this, but none of your regexes are going to work. Remember that regular expressions are designed to match textual data. While it's possible to use them to match numbers, it's not really the tool of choice.
If you have to use a regex, you need to think of the possible textual representations of a number range.
For your example 1, that would be:
As a regex:
^(?:\d|[1-3]\d|4[0-5])$
The ^
and $
anchors make sure that the entire string is evaluated; the (?:...)
groups the alternation and "shields" it from the anchors.
For your example 3:
As a regex:
^(?:1[6-9]|[2-5]\d|6[0-5])$
For your example 5:
As a regex:
^(?:\d{1,5}|1[0-4]\d{4}|150000)$
And so on.
Adding decimal places is not very difficult:
\.\d{2}
works for exactly two decimal places\.\d{1,3}
for 1 to 3 decimal places(?:\.\d{1,2})
for 0 to 2 decimal places (and the dot is only allowed if at least one digit follows).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