我有一个字符串:
0000000000<table blalba>blaalb<tr>gfdg<td>kgdfkg</td></tr>fkkkkk</table>5555
我想将table
和/table
之间的文字替换为:&#34;&#34;,删除此文字以仅显示00000000005555。
当它在一行上时,它可以工作:
chaineHtml = chaineHtml.replaceFirst("[^<title>](.*)[</title>$", "");
但与table
相同的失败。
答案 0 :(得分:3)
这个正则表达式应该有效:
html = html.replaceAll("(?is)<table.+?/table>", "");
(?is)
将使多行匹配并忽略大小写。
但我建议您不要使用正则表达式来操纵HTML,因为它可能容易出错。
答案 1 :(得分:0)
试试这个
s = s.replaceAll("<table.+/table>", "");
答案 2 :(得分:0)
[^<table>]
我认为这并不意味着你的意思。
不是&#34;不等于&lt; table&gt;&#34;的字符串。相反,它意味着&#34; 字符不等于&lt;或t或a或b或l或e或&gt;&#34;。 &#34; [^ ...]&#34;被称为negative character class。
将正则表达式更改为
(.*?)<table>.*?</table>(.*?)
替换为
$1$2
它会给你你想要的结果。
请考虑将The Stack Overflow Regular Expeession FAQ加入书签以供将来参考。底部包含一个在线正则表达式测试人员列表,您可以在其中自行尝试。您可能还想查看名为&#34; Character Classes&#34;并且,如@anubhava所述:&#34;一般信息&gt;不要使用正则表达式来解析HTML&#34;
答案 3 :(得分:0)
String resultString = subjectString.replaceAll("<table.*?table>", "");
<强>解释强>
Match the characters “<table” literally «<table»
Match any single character that is not a line break character «.*?»
Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the characters “table>” literally «table>»
答案 4 :(得分:0)
如果您不熟悉其概念,请不要使用正则表达式!
您的问题有一个简单的普通java解决方案:
String begin = "<table";
String end = "</table>";
String s = "0000000001<table blalba>blaalb<tr>gfdg<td>kgdfkg</td></tr>fkkkkk</table>4555";
int tableIndex = s.indexOf(begin);
int tableEndIndex = s.indexOf(end, tableIndex);
while (tableIndex > -1) {
s = s.substring(0, tableIndex) + s.substring(tableEndIndex + end.length());
tableIndex = s.indexOf("<table");
tableEndIndex = s.indexOf("</table>", tableIndex);
}
答案 5 :(得分:-1)
这是我在某处发现的一个出色的解决方案: 使用正则表达式
[\s\S]
适合任何字符,包括换行符,因为它适合任何空格或非空格字符。所以在你的情况下会给出:
s = s.replaceAll("<table[\\s\\S]+/table>", "");
双反斜杠是为了逃避反斜杠。
另一种可能性是
(.|\n)
是任何字符(换行符除外)或换行符,它给出:
s = s.replaceAll("<table(.|\n)+/table>", "");
出于某种原因,在我的计算机上,在某些组合中,当我使用(.|\n)+
正则表达式运行到一个奇怪的循环并进入堆栈溢出时:
线程“main”java.lang.StackOverflowError中的异常 at java.lang.Character.codePointAt(Character.java:4668) at java.util.regex.Pattern $ CharProperty.match(Pattern.java:3693)
当我使用[\s\S\]+
时,这不会发生。我不知道为什么。