是否有一个好方法从Java字符串中删除HTML ?一个简单的正则表达式

replaceAll("\\<.*?>", "") 

会起作用,但有些东西像&将不能正确地转换,并且两个尖括号之间的非html将被删除(即。*?在正则表达式中将消失)。


当前回答

使用JSoup保留新行信息的一种方法是在所有新行标记之前使用一些虚拟字符串,执行JSoup并将虚拟字符串替换为“\n”。

String html = "<p>Line one</p><p>Line two</p>Line three<br/>etc.";
String NEW_LINE_MARK = "NEWLINESTART1234567890NEWLINEEND";
for (String tag: new String[]{"</p>","<br/>","</h1>","</h2>","</h3>","</h4>","</h5>","</h6>","</li>"}) {
    html = html.replace(tag, NEW_LINE_MARK+tag);
}

String text = Jsoup.parse(html).text();

text = text.replace(NEW_LINE_MARK + " ", "\n\n");
text = text.replace(NEW_LINE_MARK, "\n\n");

其他回答

使用HTML解析器而不是正则表达式。这对于Jsoup来说非常简单。

public static String html2text(String html) {
    return Jsoup.parse(html).text();
}

Jsoup还支持根据可定制的白名单删除HTML标记,如果您只想允许<b>, <i>和<u>,这是非常有用的。

参见:

RegEx匹配打开标记,但XHTML自包含标记除外 主要的Java HTML解析器的优缺点是什么? JSP/Servlet web应用中的跨站防护

如果你是为Android编写程序,你可以这样做……

androidx.core.text.HtmlCompat.fromHtml(指令,HtmlCompat.FROM_HTML_MODE_LEGACY) .toString ()

要获得格式化的纯html文本,您可以这样做:

String BR_ESCAPED = "&lt;br/&gt;";
Element el=Jsoup.parse(html).select("body");
el.select("br").append(BR_ESCAPED);
el.select("p").append(BR_ESCAPED+BR_ESCAPED);
el.select("h1").append(BR_ESCAPED+BR_ESCAPED);
el.select("h2").append(BR_ESCAPED+BR_ESCAPED);
el.select("h3").append(BR_ESCAPED+BR_ESCAPED);
el.select("h4").append(BR_ESCAPED+BR_ESCAPED);
el.select("h5").append(BR_ESCAPED+BR_ESCAPED);
String nodeValue=el.text();
nodeValue=nodeValue.replaceAll(BR_ESCAPED, "<br/>");
nodeValue=nodeValue.replaceAll("(\\s*<br[^>]*>){3,}", "<br/><br/>");

要获得格式化的纯文本,将<br/>更改\n,并更改最后一行:

nodeValue=nodeValue.replaceAll("(\\s*\n){3,}", "<br/><br/>");

我知道这个问题已经有一段时间没有被问到了,但我找到了另一个解决方案,这对我来说很有效:

Pattern REMOVE_TAGS = Pattern.compile("<.+?>");
    Source source= new Source(htmlAsString);
 Matcher m = REMOVE_TAGS.matcher(sourceStep.getTextExtractor().toString());
                        String clearedHtml= m.replaceAll("");

您可以使用此代码删除HTML标记,包括换行符。

function remove_html_tags(html) {
    html = html.replace(/<div>/g, "").replace(/<\/div>/g, "<br>");
    html = html.replace(/<br>/g, "$br$");
    html = html.replace(/(?:\r\n|\r|\n)/g, '$br$');
    var tmp = document.createElement("DIV");
    tmp.innerHTML = html;
    html = tmp.textContent || tmp.innerText;
    html = html.replace(/\$br\$/g, "\n");
    return html;
}