日期:2014-05-20  浏览次数:20935 次

求个匹配以<title>开头</title>结尾的正则表达式
匹配以 <title> 开头 </title> 结尾的字符串, 能对付嵌套.  

如: <title> 21212145424<title> 21212145424发动@#$%机雕刻家大家fdf </title> fdf </title>

匹配结果应当为: <title> 21212145424发动@#$%机雕刻家大家fdf </title> 的正则表达式.

===============================================================================
自己试了:<title> .*? </title>

但匹配的结果是: <title> 21212145424<title> 21212145424发动@#$%机雕刻家大家fdf </title>,

不能得到想要的结果

------解决方案--------------------
Java code

public static void main(String[] args) {
        String str = " <title> 21212145424<title> 21212145424发动@#$%机雕刻家大家fdf </title> fdf </title>";
        Matcher m = Pattern.compile("<title>(?!.*?<title>).*?</title>").matcher(str);
        while(m.find()){
            System.out.println(m.group());
        }
    }

------解决方案--------------------
.*?那个"?"去掉就可以了
------解决方案--------------------
<title>[^<>]*</title>
------解决方案--------------------
Java code

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestConvert {
    public static void main(String[] args) {
    String html_line = "<title> 21212145424<title> 21212145424发动@#$%机雕刻家大家fdf </title> fdf </title>";

    String result = null;
    Pattern p = Pattern.compile(".*(<title>.*?</title>).*");//
    Matcher m = p.matcher(html_line);//开始编译
    while (m.find()) {
        result = m.group(1);//获取被匹配的部分
    }
    System.out.println(result);
    }
}

------解决方案--------------------
探讨

<title>([^<>]*)</title>