所以我在正则表达式方面遇到了麻烦。所以我只想检测字符串是否包含任何数字。如果有则匹配。
Case 1 "abc" -> false
Case 2 "165-45" ->true
Case 3 "ab3b" -> true
Case 4 "1231asdf" -> true
Case 5 "asdfasd123213" -> true
Case 6 "12-465" -> true
Case 7 "ASDSAD" -> False
到目前为止,我得到了案例 3 和 4,但失败了
if(query.matches("[0-9,-]+$")){
// contains a number
System.out.println("match");
} else{
// does not contain a number
System.out.println("not match");
}
最佳答案
为什么要费心使用逗号、连字符和输入结束符?
此外,matches
方法也匹配整个String
。
我会使用以下内容:
System.out.println(Pattern.compile("\\d").matcher(query).find());
完整示例:
String[] queries = { "abc", // -> false
"165-45", // -> true
"ab3b", // -> true
"1231asdf", // -> true
"asdfasd123213", // -> true
"12-465", // -> true
"ASDSAD" // -> false
};
Pattern p = Pattern.compile("\\d");
for (String s : queries) {
System.out.println(p.matcher(s).find());
}
输出
false
true
true
true
true
true
false
关于Java正则表达式如果字符串包含数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23642322/