Java regex returning false

I am new to java regex. I wrote the following code to check a number without a number. If we enter any number without a digit, it should return false. for me below the code always returns false. What is wrong here?

regularexpression package;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NumberValidator {

    private static final String NUMBER_PATTERN = "\\d";
    Pattern pattern;

    public NumberValidator() {
        pattern = Pattern.compile(NUMBER_PATTERN);
    }

    public boolean validate(String line){
        Matcher matcher = pattern.matcher(line);
        return matcher.matches();
    }

    public static void main(String[] args) {

        NumberValidator validator = new NumberValidator();

        boolean validate = validator.validate("123");

        System.out.println("validate:: "+validate);
    }

}
+5
source share
2 answers

From the Java documentation:

The match method attempts to match the entire input sequence with the pattern.

Your regular expression matches a single digit, not a number. Add +after \\din line with other numbers:

private static final String NUMBER_PATTERN = "\\d+";

As an additional note, you can combine initialization and template declaration, which makes the constructor unnecessary:

Pattern pattern = Pattern.compile(NUMBER_PATTERN);
+10
source

matches " true, ."

- 3 , \d, "".

\d+, " ". "\\d+"

+2

All Articles