I want users to be allowed to enter numbers, up to 3 digits before the decimal place, with an optional decimal place and a maximum of 2 digits after the optional decimal place.
I want it to match: 12, 123, 123.5, 123.55, 123. I do not want it to match: abc, 1234, 123.555
What I have so far it: ^\\d{0,3}(.?)\\d{0,2}$
At the moment it is still matching 1234. I think I need to use the look behind operator somehow but I'm not sure how.
Thanks
Try this:
^\d{0,3}(?:\.\d{0,2})?$
Or better, to avoid just a .
:
^(?:\d{1,3}(?:\.\d{0,2})?|\.\d{1,2})$
Specifically, note:
^\\d{0,3}(\\.?)\\d{0,2}$
isn't correct. With the dot optional, it can match 12378
: \\d{0,3}
matches 123
, (\\.?)
doesn't match anything, and \\d{0,2}
matches 78
. Working example: http://rubular.com/r/OOw6Ucgdgq
Maybe this (untested)
^(?=.*\\d)\\d{0,3}\\.?(?<=\\.)\\d{0,2}$
Edit - the above is wrong.
@Kobi's answer is correct.
A lookahead could be added to his first version to insure a NOT just a dot or empty string.
^(?=.*\\d)\\d{0,3}(?:\\.\\d{0,2})?$
那这个呢?
/^\d{0,2}(?:\d\.|\.\d|\d\.\d)?\d?$/
You have to put the combination of decimal point and the decimal numbers optional. In your regex, only the decimal number is optional. 1234 is accepted because 123 satisfy ^\\d{0,3}, not existing decimal point satisfy (.?), and 4 satisfy \\d{0,2}.
Kobi's answer provided you the corrected regex.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.