类似的html标签,有两种情况:A:
<z:op alt="hello alt" title="demo" ... >
...<hello>Hello</hello>...
</z:op>B:
<z:op alt="hello alt" title="demo" ... />
请问如何用正则来解析以下要求:
1、提取z:op中的op
2、提取z:op中的所有属性
3、如果为非闭合标签,则提取中间内容,如:...<hello>Hello</hello>...

解决方案 »

  1.   


    String html="<z:op alt=\"hello alt\" title=\"demo\" ... >\n...<hello>Hello</hello>...\n</z:op>";
    Pattern p=Pattern.compile("(?s)<(\\w+:(\\w*))\\s+(.*?)>(.*?)</\\1>");//查找非闭合
    Matcher m=p.matcher(html);
    while(m.find())
         System.out.println(m.group(2)+","+m.group(3)+","+m.group(4));
    html="<z:op alt=\"hello alt\" title=\"demo\" ... />";//查找闭合
    p=Pattern.compile("(?s)<\\w+:(\\w*)\\s+(.*?)/>");
    m=p.matcher(html);
    while(m.find()){
        System.out.println(m.group(1)+","+m.group(2));
    }
      

  2.   

    第一个不懂啥意思,
    第二个:
     //正则提取
    public static List<String> getContext2(String html) {


    List<String> resultList = new ArrayList<String>();
            Pattern p = Pattern.compile("\"(.*?)\" ");//匹配"开头," 结尾的文档
            Matcher m = p.matcher(html );//开始编译
            while (m.find()) {
             String str=m.group(1);
             resultList.add(str);//获取被匹配的部分
            }
            return resultList;
        }
    不过说实在的,这个应该用dom解析更合适一些。
      

  3.   

    其实就是 这样的标签很多 但他们有一个相同点 都是 z: 开头的op也是要提取的一部分
      

  4.   

    用dom4j的xpath解析,应该不难。