java中Matcher类的find()和matches()的区别
代码示例
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @Author :
* @Date :Created in 2022/10/28 10:32
* @Description:
*/
public class TestTwo {
public static void main(String[] args) {
String str = "m222";
//0至9,出现一次或多次
Pattern p = Pattern.compile("[0-9]+");
Matcher m = p.matcher(str);
System.out.println("m.matches->>"+m.matches());
if(m.find()){
System.out.println("m.find->>true");
System.out.println("m.start->>"+m.start());
System.out.println("m.end->>"+m.end());
System.out.println("m.child->>"+str.substring(m.start(),m.end()));
} else {
System.out.println("m.find->>false");
}
//str.matches()底层还是:Pattern p = Pattern.compile("[0-9]+"); Matcher m = p.matcher(str);
System.out.println(str.matches("[0-9]+"));
}
}
运行结果

解释
这时会有点疑惑,为什么matches方法返回了false,而find返回了true呢?
因为matches方法的匹配机制是针对整个字符串的,按照上面代码给出的正则表达式,如果想要通过matches方法返回true,则str必须全部是数字。
而find方法则不同,它属于搜索匹配。比如传入str="222m333",find方法会将这个字符串拆成若干个子字符串,只要有一个或多个子字符串符合正则表达式,则返回true。并且find方法还有类似于Map集合中next方法的功能。例如str=“222m333”时,第一次调用find方法,此时Matcher对象m的start值会为0、end值会为3。而再次调用时会start值会变成4、end值变成7。如果我们再调用一次find,就会直接返回false了。

浙公网安备 33010602011771号