如何将HTML文本转换为纯文本?

MGS*_*hil 23 html java

朋友我必须从url解析描述,其中解析的内容有很少的html标签,所以如何将其转换为纯文本.

Sea*_*oyd 22

摆脱HTML标签很简单:

// replace all occurrences of one or more HTML tags with optional
// whitespace inbetween with a single space character 
String strippedText = htmlText.replaceAll("(?s)<[^>]*>(\\s*<[^>]*>)*", " ");
Run Code Online (Sandbox Code Playgroud)

但不幸的是,要求从未如此简单:

通常情况下,<p><div>元件需要一个单独的处理,可能存在与CDATA块>字符(例如JavaScript的),该弄乱正则表达式等


Kan*_*dha 8

您可以使用此单行删除html标记并将其显示为纯文本.

htmlString=htmlString.replaceAll("\\<.*?\\>", "");
Run Code Online (Sandbox Code Playgroud)


小智 8

使用Jsoup。

添加依赖

<dependency>
  <!-- jsoup HTML parser library @ https://jsoup.org/ -->
  <groupId>org.jsoup</groupId>
  <artifactId>jsoup</artifactId>
  <version>1.13.1</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

现在在你的java代码中:

public static String html2text(String html) {
        return Jsoup.parse(html).wholeText();
    }
Run Code Online (Sandbox Code Playgroud)

只需调用 html2text 方法并传递 html 文本,它将返回纯文本。


Ran*_*jit 7

是的,Jsoup将是更好的选择。只需执行以下操作即可将整个HTML文本转换为纯文本。

String plainText= Jsoup.parse(yout_html_text).text();
Run Code Online (Sandbox Code Playgroud)

  • 为了保持换行,您现在还可以使用`Jsoup.parse(html).wholeText()` (2认同)

ank*_*nfo 5

使用 HTML 解析器,例如htmlCleaner

详细答案:How to remove HTML tag in Java