[英]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?
我使用正则表达式错了吗?
试试下面的正则表达式:
private static final String DIGIT_PATTERN = "\\d+";
Why not just use 为什么不用
private static final String DIGIT_PATTERN = "\\d";
That should match if there's any number in there. 如果那里有任何数字,那应该匹配。
The most basic pattern 最基本的模式
".*[0-9].*"
works for me with your code. 适合我的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.