clankill3r
clankill3r

Reputation: 9543

Regex check to see if a String contains non digit fails

Why does this fail?

String n = "h107";
if (n.matches("\\D+")) {
  System.out.println("non digit in it");
}

I had a night sleep over it, and I still not get it. I got a solution now:

if (n.matches(".*\\D+.*")) {

But in my (maybe lack of knowledge) the first one should also match. Cause if it has to match a complete String, then what's the point of a '^' character for a line beginning.

Upvotes: 4

Views: 1401

Answers (2)

Salman Arshad
Salman Arshad

Reputation: 272086

String.matches returns true if the entire string matches the pattern. Simply change your regular expression to \d+ which returns true if entire string consists of digits:

String n = "h107";
if (!n.matches("\\d+")) {
     System.out.println("non digit in it");
}

Upvotes: 2

fge
fge

Reputation: 121712

That is the recurring problem of .matches(): it is misnamed. It does NOT do regex matching. And the problem is that even other languages have fallen prey to that misnaming (python is one example).

The problem is that it will try to match your whole input.

Use a Pattern, a Matcher and .find() instead (.find() does real regex matching, ie find text that matches anywhere in the input):

private static final Pattern NONDIGIT = Pattern.compile("\\D");

// in code
if (NONDIGIT.matcher(n).find())
    // there is a non digit

You should in fact use a Pattern; String's .matches() will recompile a pattern each time. With a Pattern it is only compiled once.

Upvotes: 7

Related Questions