让我们看看实际使用的正则表达式:
^([+\-]?[0-9\,]*(\.[0-9]*)?)$
这匹配12.
因为你的第二部分是(\.[0-9]*)
。注意*
表示零个或多个,因此数字是可选的。
这也符合1,,2
因为您在第一个字符类中包含了逗号[0-9\,]
。所以实际上你的正则表达式会匹配,,,,,,,,
以及。
这可以在没有正则表达式的情况下解决,但是如果你need一个正则表达式,你可能想要这样的东西:
^[+-]?[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)?$
细分:
^ # match start of string
[+-]? # matches optional + or - sign
[0-9]{1,3} # match one or more digits
(,[0-9]{3})* # match zero or more groups of comma plus three digits
(\. # match literal dot
[0-9]+ # match one or more digits
)? # makes the decimal portion optional
$ # match end of string
要在 Java 中使用它,你需要类似的东西:
ets = ","; // commas don't need to be escaped
eds = "\\."; // matches literal dot
regex = "^[+-]?[0-9]{1,3}(" + ets + "[0-9]{3})*(" + eds + "[0-9]+)?$"