使用小数分隔符和千位分隔符验证小数

2024-04-16

您好,我使用这个正则表达式来验证带有小数分隔符和千位分隔符的数字

ets = "\\,";
eds = "\\.";
"^([+\\-]?[0-9" + ets + "]*(" + eds + "[0-9]*)?)$"

但是这个fail(它不应该接受)对于我的两个单元测试用例,

12., and 1,,2,有人可以帮忙吗?

注意:这项工作适用于1..2.


让我们看看实际使用的正则表达式:

^([+\-]?[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]+)?$"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用小数分隔符和千位分隔符验证小数 的相关文章

随机推荐