让我们看看实际使用的正则表达式:
^([+\-]?[0-9\,]*(\.[0-9]*)?)$
这匹配12.,因为您的第二部分是(\.[0-9]*)。请注意,* 表示零或多个,因此数字是可选的。
这也匹配1,,2,因为您在第一个字符类[0-9\,] 中包含了逗号。所以实际上你的正则表达式也会匹配,,,,,,,,。
这可以在没有正则表达式的情况下解决,但是如果您需要一个正则表达式,您可能需要这样的东西:
^[+-]?[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]+)?$"