Reputation: 13
I am trying to write a regular expression for accepting positive numbers from 1-99 and accepting decimals up to 2 places I have written this expression
([1-9]|[1-9][0-9])(.[0-9]{1,2})?
But when I tested the expression, it accepted 100 and decimals up to 3 places, while I wanted decimals only up to 2 places and 100 should not be accepted.
Upvotes: 1
Views: 5172
Reputation: 46826
This seems to work for me:
/^[1-9][0-9]?(\.[0-9]{1,2})?$/
As David said, you need to escape your .
, or it matches any character, including a digit.
Upvotes: 3
Reputation: 3176
I would go with this ^(?:\d[1-9]|[1-9]|[1-9][0-9])(?:\.(?:[0-9][1-9]|[1-9]))?$
0 FAIL
0.0 FAIL
0.00 FAIL
0.1 FAIL
0.12 FAIL
1 PASS
12 PASS
135 FAIL
1.00 FAIL?
01.35 PASS
10.35 PASS
12.01 PASS
12.1 PASS
12.23 PASS
12.234 FAIL
EDIT ANSWER AFTER FIRST COMMENT.
Upvotes: -1
Reputation: 14237
This will match 1-99 and up to 2 decimal places.
((0?[1-9]|[1-9][0-9])\.[0-9]{1,2})
Upvotes: -1
Reputation: 72850
Escape the .
which matches any character as \.
. You have no delimiters around this, so note that this would match, for example, 91.23 in the string 191.234.
([1-9]|[1-9][0-9])(\.[0-9]{1,2})?
Upvotes: 3