Reputation: 429
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.
Upvotes: 0
Views: 74
Reputation: 784968
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.
Upvotes: 0
Reputation: 31689
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.)
Upvotes: 3
Reputation: 19506
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.
Upvotes: 1
Reputation: 76
\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"]+);
Upvotes: -1