Regex to accept only 2 places after
Hi all i need all these possible cases to be valid
开发者_如何学编程123
123.1
123.12
I tried this ^[0-9]*\.[0-9]{2}$ or ^[0-9]*\.[0-9][0-9]$
but does not works can any one help me out
Try this:
^[0-9]*(\.[0-9]{1,2})?$
Based on your second example, but allows either one or two decimal places, and makes the whole decimal part optional.
[EDIT]
OP has altered the criteria of the question -- see comments below. He now wants digits prior to the decimal point to only allow up to six digits and has asked me to edit the answer to suit.
All that is needed is to replace the *
(for any number of digits) with {0,6}
(for between zero and six digits). If you wanted at least one digit, then it would be {1,6}
.
Here is the modified regex:
^[0-9]{0,6}(\.[0-9]{1,2})?$
try ...
^\d{1,6}(?:\.\d{1,2})?$
* Edited as suggested to make it non-capturing.
almost got it...
^[0-9]*(\.[0-9]{1,2})?$
You might also need to worry about figures that start with a dot, treat the dot without any numbers as invalid, and reject empty numbers:
^(?:\d+|\d*\.\d{1,2})$
This accepts 1
, .1
, 1.0
but rejects .
, 1.
, and (empty number).
Try this as per all your requirements
^(\d{0,6})(\.\d{1,2})?$
精彩评论