user1882812
user1882812

Reputation: 946

Regex test whether string contains digits

I wanted to test if a string contains numbers (at least one number) so I tried out this:

public class Test {
private static final String DIGIT_PATTERN = "^(?=.*\\d)";
private static final Pattern DIGIT_PATTERN_COMPILED = Pattern.compile(DIGIT_PATTERN);

/**
 * 
 * @param args
 */
public static void main(String[] args) {
    String passwordOne = "123";
    String passwordTwo = "abc";

    Matcher matcher = null;

    matcher = DIGIT_PATTERN_COMPILED.matcher(passwordOne);

    if(!matcher.matches()) {
        System.out.println("Password " + passwordOne + " contains no number");
    } else {
        System.out.println("Password " + passwordOne + " contains number");
    }

    matcher = DIGIT_PATTERN_COMPILED.matcher(passwordTwo);

    if(!matcher.matches()) {
        System.out.println("Password " + passwordTwo + " contains no number");
    } else {
        System.out.println("Password " + passwordTwo + " contains number");
    }   
}
}

Unfortunately both if clauses print out that it contains no number. Am I using the regex wrong?

Upvotes: 2

Views: 5881

Answers (3)

venite
venite

Reputation: 313

The most basic pattern

".*[0-9].*"

works for me with your code.

Upvotes: 3

SQB
SQB

Reputation: 4078

Why not just use

private static final String DIGIT_PATTERN = "\\d";

That should match if there's any number in there.

Upvotes: 1

hsz
hsz

Reputation: 152206

Just try with following regex:

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

Upvotes: 2

Related Questions