gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:02:12 25 4
gpt4 key购买 nike

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

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

要在 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]+)?$"

关于java - 使用小数分隔符和千位分隔符验证小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19641061/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com