我要求判断一个字符串中是否包含cat 根据在网上查的资料 写出程序如下import java.util.regex.*;class Test {
public static void main(String[] args) {
Pattern p = Pattern.compile("cat");
Matcher m = p.matcher("tomcat");
System.out.print(m.matches());
}
}
结果为false  除非改成这样 p.matcher("cat"); 结果才为true为什么会这样?正则表达式的写法应该就是cat啊,为什么会不匹配呢?给我的感觉要完全匹配他才承认,那如果这样的话定位符 ^ 的意义是什么呢?比如Pattern.compile("^cat"); 应该是匹配cat开头的所有字符串,但是我试了一下,也只有cat完全匹配结果才为true。很郁闷啊,望指点一下

解决方案 »

  1.   

    public static void main(String[] args) {
    Pattern p = Pattern.compile("cat");
    Matcher m = p.matcher("tomcat");
    if(m.find()){
    System.out.println("true");
    }else{
    System.out.println("false");
    }

    //System.out.print(m.matches());
    }
      

  2.   

    Matcher.matches() ;
    正如你所料,是确定一个字符串是否准确地匹配了一个模式。
      

  3.   

    还有一种方式确定一个字符串是否准确地匹配了一个模式。 Pattern p = Pattern.compile("\\A"+"cat"+"\\z");
    Matcher m = p.matcher("tomcat");
    System.out.print(m.matches());