Java模式匹配经典代码如下:
Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaab");
boolean b = m.matches();
但是我不想要这个样子的,太死板了,比如我希望以下代码能够匹配成功:Pattern p = Pattern.compile("ab");
Matcher m = p.matcher("wwwabzzz"); 我想说的是,我不仅希望能够匹配其中一部分能够匹配得到的,而且也希望抓取能够匹配到底那部分字符串例如代码: start <table ....> <tr>tablecontent</tr></table> end
我希望能够通过匹配 <table .*?>.*?</table>
就能够抓取到table的内容,丢弃其它不要的部分。
p.matcher(""); 这个代码太傻了,只能匹配整个字符串。
Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaab");
boolean b = m.matches();
但是我不想要这个样子的,太死板了,比如我希望以下代码能够匹配成功:Pattern p = Pattern.compile("ab");
Matcher m = p.matcher("wwwabzzz"); 我想说的是,我不仅希望能够匹配其中一部分能够匹配得到的,而且也希望抓取能够匹配到底那部分字符串例如代码: start <table ....> <tr>tablecontent</tr></table> end
我希望能够通过匹配 <table .*?>.*?</table>
就能够抓取到table的内容,丢弃其它不要的部分。
p.matcher(""); 这个代码太傻了,只能匹配整个字符串。
Pattern p = Pattern.compile("<table[^>]*>(.*?)</table>");
Matcher m = p.matcher(str);
boolean flag = m.find();
if(flag){
System.out.println(m.group(1));
}
String s = "<table id='44'>丰富风范仿佛<table id='33'>hahahaha<table id='22'>100<TABLE id='11'>center</TABLE>11</table>hehehehe</table>444444</table>";
String reg = "(>)?.*?(<TABLE.*?>).*?(</TABLE>).*?(table>)";
Pattern pa = Pattern.compile(reg);
Matcher ma = pa.matcher(s);
boolean r=ma.find();
System.out.println(ma.group());
匹配出来不是我想要的结果: >丰富风范仿佛<table id='33'>hahahaha<table id='22'>100<TABLE id='11'>center</TABLE>11</table>
我希望能够匹配到<TABLE ... >的外面套一层的那个的table的全部内容:<table id='22'>100<TABLE id='11'>center</TABLE>11</table>
String reg = "<table[^>]*>[^<]*<TABLE[^>]*>.*?</TABLE>.*?</table>";
Pattern pa = Pattern.compile(reg);
Matcher ma = pa.matcher(s);
boolean flag = ma.find();
if(flag){
System.out.println(ma.groupCount());
for(int i=0; i<=ma.groupCount(); i++){
System.out.println(i+":"+ma.group(i));
}
}