使用JavaScript中的正则表达式验证货币金额

Validate currency amount using regular expressions in JavaScript

本文关键字:验证 货币 金额 正则表达式 JavaScript 使用      更新时间:2023-09-26

可能重复:
什么';s是一个C#正则表达式;我会验证货币,浮动还是整数?

如何在JavaScript中使用正则表达式验证货币金额?

小数分隔符:,

十、百等分隔符:.

图案:###.###.###,##

有效金额示例:

1
1234
123456
1.234
123.456
1.234.567
1,23
12345,67
1234567,89
1.234,56
123.456,78
1.234.567,89

编辑

我忘了提到以下模式也是有效的:###,###,###.##

仅根据您给出的标准,我就想到了这一点。

/(?:^'d{1,3}(?:'.?'d{3})*(?:,'d{2})?$)|(?:^'d{1,3}(?:,?'d{3})*(?:'.'d{2})?$)/

演示

这很丑陋,而且随着你发现更多需要匹配的病例,情况只会变得更糟。您最好找到并使用一些验证库,而不是尝试自己完成这项工作,尤其是不在单个正则表达式中。

更新以反映添加的要求


关于以下评论再次更新

它将匹配123.123,123(三个尾随数字而不是两个),因为它将接受逗号或句点作为千位和十进制分隔符。为了解决这个问题,我现在基本上将表达式加倍;它要么用逗号作为分隔符并以句点作为基点来匹配整件事,要么用句点作为分隔符和逗号作为基点来匹配整件事。

明白我说的越来越混乱是什么意思了吗?(^_^)


下面是详细的解释:

(?:^           # beginning of string
  'd{1,3}      # one, two, or three digits
  (?:
    '.?        # optional separating period
    'd{3}      # followed by exactly three digits
  )*           # repeat this subpattern (.###) any number of times (including none at all)
  (?:,'d{2})?  # optionally followed by a decimal comma and exactly two digits
$)             # End of string.
|              # ...or...
(?:^           # beginning of string
  'd{1,3}      # one, two, or three digits
  (?:
    ,?         # optional separating comma
    'd{3}      # followed by exactly three digits
  )*           # repeat this subpattern (,###) any number of times (including none at all)
  (?:'.'d{2})? # optionally followed by a decimal perioda and exactly two digits
$)             # End of string.

让它看起来更复杂的一件事是里面所有的?:。通常,正则表达式也会捕获(返回匹配项)所有子模式。?:所做的只是说不必费力地捕获子模式。因此,从技术上讲,如果你去掉所有的?:,完整的东西仍然会匹配你的整个字符串,这看起来更清晰:

/(^'d{1,3}('.?'d{3})*(,'d{2})?$)|(^'d{1,3}(,?'d{3})*('.'d{2})?$)/

此外,regular-expressions.info也是一个很好的资源。

这适用于您的所有示例:

/^(?:'d+(?:,'d{3})*(?:'.'d{2})?|'d+(?:'.'d{3})*(?:,'d{2})?)$/

作为一个详细的正则表达式(不过在JavaScript中不支持):

^              # Start of string
(?:            # Match either...
 'd+           # one or more digits
 (?:,'d{3})*   # optionally followed by comma-separated threes of digits
 (?:'.'d{2})?  # optionally followed by a decimal point and exactly two digits
|              # ...or...
 'd+           # one or more digits
 (?:'.'d{3})*  # optionally followed by point-separated threes of digits
 (?:,'d{2})?   # optionally followed by a decimal comma and exactly two digits
)              # End of alternation
$              # End of string.

除了(刚刚添加的?)123.45情况外,它处理上面的所有内容:

function foo (s) { return s.match(/^'d{1,3}(?:'.?'d{3})*(?:,'d'd)?$/) }

您需要处理多种分隔符格式吗?