Hasith Magage
Hasith Magage

Reputation: 553

Regex check if a string contains only digits doesn't work

This is my code and I have no idea why it returns false

    "A123".matches("\\D+");

Upvotes: 1

Views: 244

Answers (3)

Rahul Tripathi
Rahul Tripathi

Reputation: 172408

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.

Upvotes: 1

fge
fge

Reputation: 121712

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.

Upvotes: 1

Jens
Jens

Reputation: 69440

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.

Upvotes: 3

Related Questions