public class Test { public static void main(String[] args) {
Pattern p = Pattern.compile("^s[\\d]{3}m$");
Matcher m = p.matcher("<P>s123m</P>");
while(m.find()) {
System.out.println(m.group());
}
}
}为什么这个程序抓不出来?
但是吧开头的^ 和结尾的$ 去掉 就可以抓出来了。
有人能帮忙解释下吗?

解决方案 »

  1.   

    边界匹配器
    ^  行的开头
    $  行的结尾你都看下 api啊 你这个正则的意思 是必须以 s开通 m结尾懂了吧
      

  2.   


    Matcher m = p.matcher("<P>s123m </P>"); 
    你这个字符串明显就不是以 s开头且以m结尾的嘛
    你是< 开头 >结尾的,所以没有匹配到,当然没有结果
    楼上的说的得清楚,你也说知道,怎么还会不理解哩
      

  3.   

     Matcher m = p.matcher("s123m  </P>");
    这样就匹配了
      

  4.   


    public class RegexTest {
    public static void main(String[] args){
    String str="<P>s123m</P>";
            Pattern pattern=Pattern.compile("[^</?p>](\\w+)",Pattern.CASE_INSENSITIVE);
    Matcher ma=pattern.matcher(str);
    if(ma.find()){
    System.out.println(ma.group());
    }
    }
    }
      

  5.   

    因为你没有写对,呵呵
    (" <P>s123m </P>")匹配中间的s123m是不是; 
    用两个断言就可以
    (?<=<P>)\\w*\\s*(?=</P>);//断言一个位置前面是<P>然后在这个位置跟着\\w*\\s*然后之后的位置得后面是一个</P>