[英]Regex check if a string contains only digits doesn't work
这是我的代码,我不知道为什么它返回false
"A123".matches("\\D+");
it must be: 一定是:
"A123".matches("^\\d+$");
lowercase d
stands for a digit ^
for the beginning of the string and ^
for the end of the string. 小写字母d
代表数字^
,代表字符串的开头, ^
代表字符串的结尾。
It is because you are yet another victim among the tens/hundreds of Java devs who are bitten daily by the fact that .matches()
is misnamed. 这是因为您是成百上千的Java开发人员中的另一个受害者,这些Java开发人员每天都因.matches()
名称.matches()
而被咬。
It will try and match the whole input . 它将尝试匹配整个输入 。 This is not what you want. 这不是您想要的。
You have to go through a Pattern
, a Matcher
and .find()
instead: 您必须通过Pattern
, Matcher
和.find()
来代替:
private static final Pattern NONDIGIT = Pattern.compile("\\D");
// Test whether there is any nondigit character in a string:
NONDIGIT.matcher(theString).find();
You should especially do that since anyway .matches()
will recompile a Pattern
each time; 您应该特别这样做,因为无论如何.matches()
每次都会重新编译一个Pattern
; here, you have only one Pattern
. 在这里,您只有一个Pattern
。
You can try this: 您可以尝试以下方法:
"A123".matches("[0-9]+")
Also as you have tagged it as Java then there is an alternate way to use NumberUtil.isNumber(String str) from Apache which can check this for you. 同样,由于您已将其标记为Java,所以还有另一种使用Apache的NumberUtil.isNumber(String str)的方法 ,可以为您检查此情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.