String string = "342中国";
String regex = "\\d*"; // "^\\d*$"
if(string.matches(regex)){
System.out.println("匹配");
}else {
System.out.println("不匹配");
}
matches方法结果是不匹配
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(string);
if(m.find()){
System.out.println("匹配");
}else{
System.out.println("不匹配");
}
find方法结果是匹配
解释如下:
find()方法是部分匹配,是查找输入串中与模式匹配的子串,如果该匹配的串有组还可以使用group()函数。
matches()是全部匹配,是将整个输入串与模式匹配,如果要验证一个输入的数据是否为数字类型或其他类型,一般要用matches()。
find()对字符串进行匹配,匹配到的字符串可以在任何位置.
Java代码示例:
Pattern p=Pattern.compile("\\d+");
Matcher m=p.matcher("22bb23");
m.find();//返回true
Matcher m2=p.matcher("aa2223");
m2.find();//返回true
Matcher m3=p.matcher("aa2223bb");
m3.find();//返回true
Matcher m4=p.matcher("aabb");
m4.find();//返回false