下面这段<div id=\"listheadline\">(.*?)<div class=\"mainNextPage\"> 我匹配 <div id=\"listheadline\"> 或者<div class=\"mainNextPage\">都可以匹配到但匹配<div id=\"listheadline\">(.*?)<div class=\"mainNextPage\"> 就匹配不到了怎么回事呢

解决方案 »

  1.   

    这个表达式本来是匹配的
    这是我的源代码
    URL u = new URL(url);
    URLConnection conn = u.openConnection();
    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuffer sb = new StringBuffer();
    while((line = br.readLine())!=null){
    sb.append(line);
    }
    br.close();
    line = sb.toString();用上面的代码读出的 line 用 <div id=\"listheadline\">(.*?) <div class=\"mainNextPage\"> 能匹配到但用 下面的代码读出的 line 用 <div id=\"listheadline\">(.*?) <div class=\"mainNextPage\"> 就匹配不到2个程序读出来的代码完全一样,不要怀疑这点,只是格式 不一样
    URL u = new URL("");
    URLConnection conn = u.openConnection();
    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuffer sb = new StringBuffer();
    char[] data = new char[1024];
    int n;
    while ((n=br.read(data)) !=-1) {
    sb.append(new String(data,0,n));
    }
    br.close();
    line = sb.toString();
    String RegxCode = "<div id=\"listheadline\">(.*?)<div class=\"mainNextPage\">";
    Pattern p = Pattern.compile(RegxCode);
    Matcher m = p.matcher(line);
    if(m.find()) {
    System.out.println("ok");
    }
      

  2.   

    是不是
    String RegxCode = " <div id=\"listheadline\">(.*?) <div class=\"mainNextPage\">"; 
    中的" <div前面多个空格?
      

  3.   

    String RegxCode = "<div id=\"listheadline\">(.*?)";
    Pattern p = Pattern.compile(RegxCode);
    Matcher m = p.matcher(line);
    if(m.find()) {
    System.out.println("ok");
    System.out.println(m.group());
    }这样的话能匹配到,但也很奇怪输出的结果:
    ok
    <div id="listheadline">(.*?) 好像没什么作用
      

  4.   

    都没看懂,不知道你要做什么,采用 .*? 不能匹配出现在匹配模式上,使用 readLine() 读,其中的换行符不会被读入(也就是扔掉了)使用 read 读,会把所有的字符读入(包括换行符),改为Pattern p = Pattern.compile(RegxCode, Pattern.DOTALL);试试看
      

  5.   

    点在默认情况下不会匹配换行符,加上 Pattern.DOTALL 就可以了。
      

  6.   

    OK 
    Pattern.DOTALL 这是什么意思
      

  7.   

    可以看看 Pattern.DOTALL 的 API DOC 说明。