嗨我用这个正则表达式验证号码与小数点分隔符和千分隔符
ets = "\\,";
eds = "\\.";
"^([+\\-]?[0-9" + ets + "]*(" + eds + "[0-9]*)?)$"
Run Code Online (Sandbox Code Playgroud)
但是fail对于我的两个单元测试用例,这个(它不应该接受)
12.,并且1,,2,任何人都可以帮忙吗?
注意:这项工作适合1..2.
让我们看一下使用的实际正则表达式:
^([+\-]?[0-9\,]*(\.[0-9]*)?)$
Run Code Online (Sandbox Code Playgroud)
这符合,12.因为你的第二部分是(\.[0-9]*).请注意,这*意味着零或更多,因此数字是可选的.
这也匹配,1,,2因为您在第一个字符类中包含逗号[0-9\,].所以实际上你的正则表达式也会匹配,,,,,,,,.
这可以在没有正则表达式的情况下解决,但是如果你需要一个正则表达式,你可能想要这样的东西:
^[+-]?[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)?$
Run Code Online (Sandbox Code Playgroud)
细分:
^ # 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
Run Code Online (Sandbox Code Playgroud)
要在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]+)?$"
Run Code Online (Sandbox Code Playgroud)