简体   繁体   English

Javascript 正则表达式货币

[英]Javascript regex currency

I'm trying to create a regex that meets the following conditions:我正在尝试创建一个满足以下条件的正则表达式:

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

I've made the following but its not working as intended我做了以下但它没有按预期工作

^[0\.|1-9\d*\.]\d{2,2}$/

Using https://regexr.com/ to test使用https://regexr.com/进行测试

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.这表示匹配一个零,后面没有小数点,或者 1-9 如果后面的也是小数点之前的另一个数字。

Tim Biegeleisen beat me by a few minutes, but here's another (less sophisticated) solution: Tim Biegeleisen 比我快了几分钟,但这是另一个(不太复杂的)解决方案:

(^[0]|^[1-9]+)\.\d{2}$

https://regex101.com/r/QJ3YyQ/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 https://regex101.com/r/QJ3YyQ/4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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