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

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

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


当前回答

我经常发现我只需要去掉注释和脚本元素。这已经为我可靠地工作了15年,可以很容易地扩展到处理HTML或XML中的任何元素名称:

// delete all comments
response = response.replaceAll("<!--[^>]*-->", "");
// delete all script elements
response = response.replaceAll("<(script|SCRIPT)[^+]*?>[^>]*?<(/script|SCRIPT)>", "");

其他回答

这里是如何替换所有(HTML标签| HTML实体|空白的HTML内容)的另一个变体

content.replaceAll ("(<.*?>)|(&.*?;)|([ ]{ 2 ,})", "");其中content是一个字符串。

你可以简单地用多个replaceAll()方法像

String RemoveTag(String html){
   html = html.replaceAll("\\<.*?>","")
   html = html.replaceAll("&nbsp;","");
   html = html.replaceAll("&amp;"."");
   ----------
   ----------
   return html;
}

使用这个链接,你需要的最常见的替换: http://tunes.org/wiki/html_20special_20characters_20and_20symbols.html

这很简单,但很有效。我使用这个方法首先删除垃圾,但不是第一行,即replaceAll(“\<.*?>”,“”),然后我使用特定的关键字搜索索引,然后使用.substring(开始,结束)方法去除不必要的东西。因为这更健壮,你可以在整个html页面中准确地指出你需要什么。

另一种方法是使用javax.swing.text.html.HTMLEditorKit来提取文本。

import java.io.*;
import javax.swing.text.html.*;
import javax.swing.text.html.parser.*;

public class Html2Text extends HTMLEditorKit.ParserCallback {
    StringBuffer s;

    public Html2Text() {
    }

    public void parse(Reader in) throws IOException {
        s = new StringBuffer();
        ParserDelegator delegator = new ParserDelegator();
        // the third parameter is TRUE to ignore charset directive
        delegator.parse(in, this, Boolean.TRUE);
    }

    public void handleText(char[] text, int pos) {
        s.append(text);
    }

    public String getText() {
        return s.toString();
    }

    public static void main(String[] args) {
        try {
            // the HTML to convert
            FileReader in = new FileReader("java-new.html");
            Html2Text parser = new Html2Text();
            parser.parse(in);
            in.close();
            System.out.println(parser.getText());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

ref:从文件中删除HTML标记,只提取文本

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

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

使用Html.fromHtml

HTML标签是

<a href=”…”> <b>,  <big>, <blockquote>, <br>, <cite>, <dfn>
<div align=”…”>,  <em>, <font size=”…” color=”…” face=”…”>
<h1>,  <h2>, <h3>, <h4>,  <h5>, <h6>
<i>, <p>, <small>
<strike>,  <strong>, <sub>, <sup>, <tt>, <u>

根据Android的官方文档,HTML中的任何标签都将显示为一个通用的替换字符串,你的程序可以通过并替换为真正的字符串。

超文本标记语言formHtml方法接受一个Html。TagHandler和Html。ImageGetter作为参数以及要解析的文本。

例子

String Str_Html=" <p>This is about me text that the user can put into their profile</p> ";

Then

Your_TextView_Obj.setText(Html.fromHtml(Str_Html).toString());

输出

这是关于我的文本,用户可以放入他们的个人资料