My regex for matching decimal numbers matches "1." How can I fix it?
I got this regular expression for decimals:
开发者_如何学运维/^(\d{1,3})(\.{0,1}\d{0,2})$/
But It allows "1."
How could I fix this?
The following regex matches 1-3 digits, optionally followed by a decimal point and 1-2 digits.
/^(\d{1,3})(\.\d{1,2})?$/
Note that I also changed your .
to \.
. It is a metacharacter that matches anything, and so it has to be escaped.
/^(\d{1,3})(\.\d{1,2})?$/
I assume you're trying to match between 0 and 999.99, with 0, 1, or 2 decimals. If there are no decimals, you want no period separator. If that's the case, you want to the above.
For what it's worth, if you don't want to force a 0
at the beginning of the number, you can use the following expression:
(\d*\.)?\d+
This will match:
1
.1
1.1
This will not match:
1.
.
With some modification, this expression can still be used to force a certain number of digits:
(\d{1,3}\.)?\d{1,2}
精彩评论