javascript - 在 JavaScript 中使用正则表达式验证货币金额

标签 javascript regex currency

<分区>

Possible Duplicate:
What's a C# regular expression that'll validate currency, float or integer?

如何在 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})?$)/

http://refiddle.com/18u

它很难看,而且当你发现更多需要匹配的情况时,它只会变得更糟。您最好找到并使用一些验证库,而不是尝试自己全部完成,尤其是不要在单个正则表达式中。

更新以反射(reflect)增加的要求。


关于下面的评论再次更新。

它将匹配 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是一个很好的资源。

关于javascript - 在 JavaScript 中使用正则表达式验证货币金额,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6190312/

相关文章:

javascript - 根据正则表达式检查 json 值会抛出不是函数错误

javascript - 如何从正则表达式替换中省略特定字符串?

javascript - 多种 AngularJS 货币格式,使用 i18n(欧元、德国)

facebook-graph-api - Facebook本币支付直接退款,无需开发商处理纠纷

usability - 如何让用户在 TextField 中输入价格含增值税或不含增值税之间进行选择?

javascript - .toggle() 函数添加溢出隐藏内联

javascript - HTML5 "required"属性在 JavaScript 中提交验证之前不起作用

javascript - 通过步骤定义和页面对象在 cucumber Protractor 中实现场景大纲

python - 在带有 os.system 的 python 脚本中正确使用 ssh 和 sed

允许使用撇号和句点的正则表达式