Java – regular expression failed to check whether the string contains non numbers

Why did this fail?

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

I slept one night and I still didn't get it@ H_ 419_ 14 @ I now have the solution:

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

But in my (possibly lack of knowledge), the first one should also match If it must match a complete string, what is the focus of the '^' character at the beginning of the line

Solution

This is The recurring problem with matches() is that it is incorrectly named It does not perform regular expression matching The problem is that even other languages are victims of this error (Python is an example)

The problem is that it will try to match your entire input

Use patterns, matchers, and Find() instead of (. Find()) for true regular expression matching, that is, to 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

In fact, you should use pattern; String Matches () recompiles one pattern at a time Using pattern, it compiles only once

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>