1

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

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

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

No need for anchors; look at my answer
1

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.