这段文本如果我想要去掉包含####的最里面的<table>标签对,应该怎么做?

原字符串<table>.fdghfhgfdfgdfgdfg$$<table>dsgfdsf#####dsfkjdshf</table>$$dsfdsfdsfdsf</table>
这段文本如果我想要去掉包含####的最里面的<table>标签对,应该怎么做,也就是得到<table>.fdghfhgfdfgdfgdfg$$$$dsfdsfdsfdsf</table>

慕尼黑5688855
浏览 152回答 3
3回答

慕的地8271018

这个怎么处理都行的,不论用什么方法底层其实都是substring,如果你的<table>和</table><table>和</table>是固定,可以这样StringUitls.substringBefore("yourstr", "<table>")+StringUitls.substringAfter("yourstr","</table><table>")+StringUitls.substringAfter("yourstr","</table>")具体效果,调试下即可。

哆啦的时光机

java里不支持递归匹配, 难点. 不过我们可以用negative lookahead来做:@Testpublic&nbsp;void&nbsp;tttttt(){&nbsp;&nbsp;&nbsp;&nbsp;String&nbsp;str="<table>.fdghfhgfdfgdfgdfg$$<table>dsgfdsf#####dsfkjdshf</table>$$dsfdsfdsfdsf</table>";&nbsp;&nbsp;&nbsp;&nbsp;str=str.replaceAll("<table>(?:.(?!.*<table>))*?</table>",&nbsp;""); &nbsp;&nbsp;&nbsp;&nbsp;System.out.println(str); }结果: <table>.fdghfhgfdfgdfgdfg$$$$dsfdsfdsfdsf</table>

心有法竹

import java.util.regex.Pattern;import java.util.regex.Matcher;public class Test {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; final String str = "<table>.fdghfhgfdfgdfgdfg$$<table>dsgfdsf#####dsfkjdshf</table>$$dsfdsfdsfdsf</table>";&nbsp; &nbsp; &nbsp; &nbsp; final Pattern patt = Pattern.compile("<table>[^<]*(<table>[^<]*</table>)[^<]*</table>");&nbsp; &nbsp; &nbsp; &nbsp; final Matcher matcher = patt.matcher(str);&nbsp; &nbsp; &nbsp; &nbsp; if (matcher.find()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(matcher.group(1));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java