简体   繁体   中英

Javascript regex currency

I'm trying to create a regex that meets the following conditions:

  1. 0.01 - true
  2. 01.01 - false
  3. 122343.10 - true
  4. 123,432.10 - false
  5. 123 - false
  6. 123423.1 - false

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.

Demo

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}$

https://regex101.com/r/QJ3YyQ/4

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM