Java 将一段Html内容转换为文本

技术 置顶 精帖
0 821
peng49
peng49 2020-09-01 19:50:43
 

代码如下

  1. import static org.springframework.web.util.HtmlUtils.htmlUnescape;
  2. public class TextUtils {
  3. public static String html2text(String html) {
  4. return htmlUnescape(html) //将html中的实体转换为对应的字符串
  5. .replaceAll("</?\\w+.*?>", "") //所有的html标签替换为空
  6. .replaceAll("\\u00A0+", " ")//替换不间断空格,ASCII值是160
  7. .replaceAll("\\s+", " ")//所有特殊字符替换为空格
  8. .replaceAll(" +", " ")//将多个连续的空格替换为单个空格
  9. .trim();//去掉首尾空格
  10. }
  11. }
回帖
登录
忘记密码?