java 正则表达式 提取两个字符串中的字符串

来源:百度知道 编辑:UC知道 时间:2024/05/21 22:14:52
Pattern pattern = Pattern.compile("(<td class='row[0-9]'>)(.+?)(</table></p><hr>)");
Matcher matcher = pattern
.matcher("er<td class='row1'>你说什么<td class='row1'>也学<td class='row1'>测试</table></p><hr>");

while (matcher.find()) {
System.out.println(matcher.group(2));
}

这样写的话里面多了几个<td class='row1'>,我只想取
<td class='row1'>和</table></p><hr>中间的字符串,但中间不能包含
<td class='row1'>,

如果用 Pattern pattern = Pattern.compile("(<td class='row[0-9]'>){1}(.+?)(</table></p><hr>)");
又取不到。。。。
关键是我只想取道<td class='row1'>测试</table></p><hr>里面的这个测试两个字

如果你需要取的字符串里并不包含其它标签,
可以像下面这样做。
用[^<>]来否定

如果还需要包含其它标签,就不可以了

Pattern pattern = Pattern.compile("(<td class='row[0-9]'>)([^<]+?)(</table></p><hr>)");
Matcher matcher = pattern
.matcher("er<td class='row1'>你说什么<td class='row1'>也学<td class='row1'>测试</table></p><hr>");

while (matcher.find()) {
System.out.println(matcher.group(2));
}

唉,正则表达式学得不多,你可以把结果先搜出来,然后用replace替换
代码:
public class ClientApp {

public static void main(String[] args)
{
Pattern pattern = Pattern
.compile("(<td class='row[0-9]'>)(.+?)(</table></p><hr>)");
Matcher matcher = pattern
.matcher("er<td class='row1'>你说什么<td class='row1'>也学<td class='row1'>测试</table