为何下面的字符串无法匹配正则?String regex = "<(\\S*?)[^>]*>.*?</\1>|<.*? />";
String str = "<p>abcd</p>";

解决方案 »

  1.   


    package com.zf.test;public class Test05 { public static void main(String[] args) {
    String regex = "<(\\S.*?).*?((/>)|(</\\1>))";

    String str = "<p>abcd</p>";
    System.out.println(str.matches(regex));

    str = "<br/>";
    System.out.println(str.matches(regex));

    str = "<span>fdfsdfsd</span>";
    System.out.println(str.matches(regex));

    str = "<span>fdfsdfsd</div>";
    System.out.println(str.matches(regex));

    }}
    true
    true
    true
    false
      

  2.   

    java正则表达式中应该不能直接使用前面匹配的分组吧,你这个应该是js的使用方式。
      

  3.   

    前面这里说错了,java也可以back引用捕获组,你的表达式的问题在于斜线和反斜线没有转义,你的表达式对应的正确写法:"<(\\S*?)[^>]*>.*?<\\/\\1>|<.*?\\/>"