Regex check to check if string string contains non digit

Why does it fail?

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

      

I had a night dream and I still don't understand. I got the solution now:

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

      

But in my (perhaps lack of knowledge) the first must match. The reason is, if it must match a complete string, what is the point of the '^' character to start the line.

+3


source to share


2 answers


This is a recurring problem .matches()

: it is wrong. It does NOT do regular expression matching. And the problem is that even other languages ​​have fallen prey to this misuse (python is one example).

The problem is it will try to match all of your input.

Use Pattern

, a Matcher

and .find()

instead ( .find()

does real regex matching, that is, find text that is anywhere in the input):



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

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

      

In fact, you should be using Pattern

; String

.matches()

will recompile the template every time. With help, Pattern

it only compiles once.

+6


source


String.matches

returns true if the entire string matches the pattern. Just change your regex to \d+

one that returns true if the whole string is digits:



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

      

+1


source







All Articles