I'm trying to create a regex that meets the following conditions:
I've made the following but its not working as intended
^[0\.|1-9\d*\.]\d{2,2}$/
Using https://regexr.com/ to test
I would use this regex:
^(?!0\d)\d+\.\d{2}$
This uses a negative lookahead in the beginning to handle the requirement that the currency value can't start with zero, if another digit follows immediately afterward.
Here is another way of doing this:
^(?:0|[1-9]\d*)\.\d{2}$
This says to match a zero, followed by nothing by decimal point, or 1-9 if what follows is also another number before the decimal.
Tim Biegeleisen beat me by a few minutes, but here's another (less sophisticated) solution:
(^[0]|^[1-9]+)\.\d{2}$
https://regex101.com/r/QJ3YyQ/2
Edit: I just realized I missed an edge case. If the digits before the decimal point contained a zero, it wouldn't match. Here's an updated regex:
(^[0]|^[1-9]\d*)\.\d{2}$
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.