简体   繁体   中英

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.

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.

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:

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; here, you have only one 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM