/** <b><b> \r\n(+\t) </b><b> \r\n </b></b> \r\n(-\t) /><b> \r\n /></b> \r\n(-\t) */ public static void show(String xml) { Matcher mth = Pattern.compile("(?:<\\w+>\\s*<\\w+|</\\w+>\\s*<.|/>\\s*<.)").matcher(xml); int count = 0; StringBuffer sb = new StringBuffer(); char[] cs = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t".tocharArray(); int lastEnd = 0; while (mth.find(lastEnd)) { try { String str = mth.group(); int idx2 = str.indexOf('<',1); if (str.charAt(0) == '<' && str.charAt(1) != '/') { count++; } else if (str.charAt(0) == '<' && str.charAt(1) == '/') { if (str.charAt(idx2 + 1) == '/') { count--; } } else if (str.charAt(0) == '/') { if (str.charAt(idx2 + 1) == '/') { count--; } } sb.append(xml,lastEnd,mth.start() + str.indexOf('>') + 1).append("\r\n").append(cs,count); lastEnd = mth.start() + idx2; } catch (Exception e) { throw new RuntimeException(count + "," + lastEnd + "," + sb + "--",e); } } sb.append(xml,xml.length()); System.out.println(sb); }
(?:) 非获取匹配,不进行存储供以后使用,预查消耗字符
(?=) 正向预查,预查不消耗字符,