简体   繁体   English

正则表达式检查字符串是否仅包含数字不起作用

[英]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: 您必须通过PatternMatcher.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.

相关问题 检查字符串是否仅包含数字且使用REGEX的数字是否相同? - Check if a String only contains digits and the digits are not the same using REGEX? 用于检查字符串是否仅包含数字和运算符(但没有 2 个连续运算符)的正则表达式 - Regex expression to check if a string only contains digits and operators (but no 2 consecutive operators) 检查字符串是否仅包含数字,然后仅在不包含数字以外的字符时进行设置 - Checking if a string contains only digits and then setting it only if it doesn't contain characters other than digits 如何检查字符串是否仅包含 Java 中的数字 - How to check if a string contains only digits in Java 使用正则表达式检查 int/string 是否包含特定数字 - check a int/string contains specific digits in it using regex 正则表达式检查字符串是否仅包含字母字符 - Regex to check if string only contains alphabetical characters 正则表达式检查字符串是否仅包含一个大写字母 - Regex to check if string contains only one uppercase 正则表达式检查字符串仅包含十六进制字符 - Regex to check string contains only Hex characters 如何检查字符串只包含数字和小数点? - How to check a string contains only digits and decimal points? 如何检查字符串只包含数字和一个小数点? - How to check a string contains only digits and one occurrence of a decimal point?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM