问题描述
||
这个问题已经在这里有了答案:
解决方法
仅根据您给出的条件,这就是我的想法。
/(?:^\\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,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,\\d\\d)?$/) }
您需要处理多种分隔符格式吗?