仅根据您给出的标准,这就是我想出的。
/(?:^\d{1,3}(?:\.?\d{3})*(?:,\d{2})?$)|(?:^\d{1,3}(?:,?\d{3})*(?:\.\d{2})?$)/
http://refiddle.com/18u
这很丑陋,当你发现更多需要匹配的案例时,它只会变得更糟。您最好找到并使用一些验证库,而不是自己尝试做这一切,尤其是不要在单个正则表达式中。
已更新以反映增加的要求。
再次更新下面的评论。
它将匹配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 是一个很好的资源。