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的),该弄乱正则表达式等
您可以使用此单行删除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 文本,它将返回纯文本。
是的,Jsoup将是更好的选择。只需执行以下操作即可将整个HTML文本转换为纯文本。
String plainText= Jsoup.parse(yout_html_text).text();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
55253 次 |
| 最近记录: |