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