[英]Regex test whether string contains digits
我想測試一個字符串是否包含數字(至少一個數字),所以我嘗試了這個:
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");
}
}
}
不幸的是,如果條款打印出來,它不包含任何數字。 我使用正則表達式錯了嗎?
試試下面的正則表達式:
private static final String DIGIT_PATTERN = "\\d+";
為什么不用
private static final String DIGIT_PATTERN = "\\d";
如果那里有任何數字,那應該匹配。
最基本的模式
".*[0-9].*"
適合我的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.