0

I wrote a condition with regex str.matches("\\D+") read with Scanner but on entering char+digit this test fails for example 3x or e3 but it should not happen. It should pass any non digit occurrence anywhere in the string even if its a symbol.

3
  • 1
    Why should it pass? \D is a non-digit character. Commented Dec 10, 2013 at 17:33
  • atleast once a non digit occurrence should be there thats what i'm saying, should pass. Commented Dec 10, 2013 at 17:36
  • "str" is a string read with Scanner class Commented Dec 10, 2013 at 17:41

4 Answers 4

3

If m is a Matcher, then m.matches returns true only if the entire string matches the pattern. If you want to just check whether some part of the string matches, you can use m.find instead of m.matches. (Note: I'm not sure whether that's actually the problem you're having.)

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

2 Comments

find(), not a JDK method.
@Prashant It's a method of the Matcher class, but you're right, it's not a String class method, while matches is a method of both. If you really want to use the String version, put .* at both ends of the pattern.
1

atleast once a non digit occurrence should be there thats what i'm saying, should pass

How about this

.*\D.*

You can test it here.

2 Comments

The non-digit occurrence should occur anywhere, which means you can have anything else before or after. +, 1+, +1, 1+1. You would just replace .* with the appropriate regex if .* is too broad.
A good source to read regex, since most of the articles do not split up the examples and explain.
0

This call fails to match 3e since:

str.matches("\\D+")

is same as:

str.matches("^\\D+$")

Because String#matches takes given regex and matches the complete input.

To make sure there is at least one non-digit, you should better use this lookahead based regex:

str.matches("(?=\\d*\\D).*")

Where (?=\\d*\\D) is positive lookahead that makes sure there is at least 1 non-digit in the given input.

Comments

-1

\D matches any non-numeric character, so of course it will fail if you pass it a string with digits in it.

If you want to match only characters and numbers you could do something like:

matches("[a-zA-Z0-9"]+);

1 Comment

i just want to pass a non digit occurrence anywhere in the string even if it is a symbol.

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.