Reputation: 946
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
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
Reputation: 152206
Just try with following regex:
private static final String DIGIT_PATTERN = "\\d+";
Upvotes: 2