删除除换行符之外的 HTML 标记
我从服务器接收带有 HTML 标签的字符串。我使用 string1.replaceAll("\\<.*?>","")
等正则表达式删除这些标签,但问题是它还删除了换行符和超链接。我想保留超链接和换行符并删除其他所有内容。
I am receiving string from server having HTML tags. I am removing these tags using regular expression like string1.replaceAll("\\<.*?>","")
but the problem is that it also remove line breaks and hyperlinks. I want to keep hyperlinks and line breaks and remove everything else.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(2)
夜无邪2025-01-13 17:30:42
您可以尝试先用某种中间格式替换要保留的部分,然后在删除所有其他标签后恢复原始格式。
string1.replaceAll("\\<br.*?>", "[br]");
string1.replaceAll("\\<a href='(.*?)'.*?>(.*?)\\<.*?>", "[link='$1' desc='$2']");
string1.replaceAll("\\<.*?>","");
string1.replaceAll("\\[br\\]", "<br\\>");
string1.replaceAll("\\[link='(.*?)' desc='(.*?)']", "<a href=\"$1\">$2<\\a>");
代码未经测试,因此可能无法工作:)
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
不要使用正则表达式来解析 HTML。
要从 HTML 中完全剥离它(不是您想要的,但很简单):
有选择地剥离它,仅保留
(以及
href
属性)和
标签我建议您使用 JSoup:Don't use regexps for parsing HTML.
To strip it completely from HTML (not what you wanted, but simple to do):
To strip it selectively, retaining only
<a>
(and thehref
attribute) and<br>
tags I suggest you use JSoup: