Dio*_*oso 6 javascript regex currency
如何在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
Run Code Online (Sandbox Code Playgroud)
编辑
我忘了提到以下模式也是有效的: ###,###,###.##
Wis*_*guy 17
完全基于您给出的标准,这就是我想出的.
/(?:^\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.
Run Code Online (Sandbox Code Playgroud)
让它看起来更复杂的一件事就是?:
在那里.通常,正则表达式也会捕获(返回匹配)所有子模式.所有?:
这一切都说是不打扰捕获子模式.所以从技术上来说,如果你把所有的东西全部拿出?:
来,整个东西仍然会匹配你的整个字符串,这看起来更清晰:
/(^\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})?)$/
Run Code Online (Sandbox Code Playgroud)
作为一个冗长的正则表达式(但不支持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.
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
28576 次 |
最近记录: |