Reputation: 4542
how to validate numbers between 0 to 99999.99 using regex?
basically it should accept the values like 0.01, 0000.01, .01 and 9999.99
also it should have only two values after dot(.)
I tried something like the below but it did not work for me.
/^[0-9]{1,5}.[0-9]{2}$/
decimal is optional
Could someone help pls.
Upvotes: 0
Views: 547
Reputation: 4542
The regex ^(?:\d{1,5}(?:\.\d{1,2})?|\.\d{1,2})$
is what I was trying to get.
Upvotes: 0
Reputation: 159215
The .
character has special meaning in a regex, so you need to escape it.
Anyway, let me see if I got the rules straight:
Since the number of digits depends on the presence of the decimal point, you make the regex have two choices, separated by |
.
Choice 1 (no decimal point): [0-9]{1,5}
Choice 2 (decimal point): [0-9]{0,5}\.[0-9]{1,2}
Since you want anchors (^$
), you can either put them in both choices, or surround the choice set with parenthesis. To make it non-capturing, use (?:xxx)
.
Final regex is one of these:
/^[0-9]{1,5}$|^[0-9]{0,5}\.[0-9]{1,2}$/
/^(?:[0-9]{1,5}|[0-9]{0,5}\.[0-9]{1,2})$/
You can see the second one in effect on regex101.
Upvotes: 3
Reputation: 3619
If javascript then below regex would work:
^\d{0,5}(((\.){0})|((\.){1}\d{1,2}))$
All the above mentioned cases are satisfying.
Upvotes: 0