你好,我使用这个正则表达式来验证带有小数点和千位分隔符的数字
ets = "\\,";
eds = "\\.";
"^([+\\-]?[0-9" + ets + "]*(" + eds + "[0-9]*)?)$"
但是这个程序
失败
了(它应该被拒绝),对于我的两个单元测试用例:12.
和1,,2
,有人可以帮忙吗?注意:这适用于
1..2
。让我们来看一下实际使用的正则表达式:
^([+\-]?[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
ets = ","; // commas don't need to be escaped
eds = "\\."; // matches literal dot
regex = "^[+-]?[0-9]{1,3}(" + ets + "[0-9]{3})*(" + eds + "[0-9]+)?$"
?
来使其变为可选项。对于我上面的正则表达式,请使用 "^[+-]?[0-9]{1,3}(" + ets + "?[0-9]{3})*(" + eds + "[0-9]+)?$"
。 - NullUserException[0-9]{0,3},
@NullUserException刚刚提供了一个完整的正则表达式,适用于您的意图