String str = "<title>ABCD</title><title></title><title>afafdfsf</title>";
String reg = ????;
要得到以下结果:
ABCD 或者 <title>ABCD</title>     (<title>与</title>之间的字符串)我的reg = "(?<=<title>).*(?=</\1>)" 怎么匹配不了,问题在哪??js里一样的表达式都可以匹配!!!比较疑惑!!!
"(?<=<title>).*(?=</\\1>)" 也试过!匹配不了 

解决方案 »

  1.   

    "(?<=<(title)>).*(?=</\\1>)"
      

  2.   


    正解。
    这里有两种效果,看楼主想要的是哪一种:
    1. 
      String str = "<title>ABCD </title> <title> </title> <title>afafdfsf </title>"; 
      Pattern p = Pattern.compile("(?<=<(title)>).*(?=</\\1>)");
      Matcher m = p.matcher(str);

      while(m.find()){
        System.out.println(m.group());
     }2.
      String str = "<title>ABCD </title> <title> </title> <title>afafdfsf </title>"; 
      Pattern p = Pattern.compile("(?<=<(title)>).*?(?=</\\1>)");
      Matcher m = p.matcher(str);

      while(m.find()){
        System.out.println(m.group());
     }
      

  3.   

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;public class TagRegexTest { public static void main(String[] args) {
    String input = " <title>ABCD </title> <title> </title> <title>afafdfsf </title>";
    Pattern p = Pattern.compile("<(\\w+)>(.*?)</\\1>", Pattern.CASE_INSENSITIVE);
    Matcher m = p.matcher(input);
    int i = 1;
    while (m.find()) {
    String result = m.group(2);
    System.out.println(i++ + ": \"" + result + "\"");
    }
    }}
    输出:
    1: "ABCD "
    2: " "
    3: "afafdfsf "
      

  4.   

    "(?<=<(title)>).*(?=</\\1>)"像这样把标签名写死用“Back 引用”还有什么意义???