5

I am newbie to java regular expression. I wrote following code for validating the non digit number. If we enter any non digit number it should return false. for me the below code always return false. whats the wrong here?

package regularexpression;

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);
    }

}
2
  • You really need a Class for that??? "123".matches("\\d+") would not be enough? Commented Jul 24, 2012 at 17:25
  • Yaa.. It is true..even with that line it does work. Thanks for simplifying the code.. Commented Jul 25, 2012 at 5:41

2 Answers 2

10

From Java documentation:

The matches method attempts to match the entire input sequence against the pattern.

Your regular expression matches a single digit, not a number. Add + after \\d to matchone or more digits:

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

As a side note, you can combine initialization and declaration of pattern, making the constructor unnecessary:

Pattern pattern = Pattern.compile(NUMBER_PATTERN);
Sign up to request clarification or add additional context in comments.

3 Comments

That does not explain why the result is false. "\\d" matches "123", too. (Also, if the pattern should only match digits, it should be "^\\d+$".)
@Tomalak Thanks for the note - I added an explanation.
Ah, I see why ^ and $ are unnecessary here. Thanks.
2

matches "returns true if, and only if, the entire region sequence matches this matcher's pattern."

The string is 3 digits, which doesn't match the pattern \d, meaning 'a digit'.

Instead you want the pattern \d+, meaning 'one or more digits.' This is expressed in a string as "\\d+"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.