导出去html标签

This commit is contained in:
yuezhihang
2022-01-19 16:47:43 +08:00
parent 07ce4f1866
commit 4821c6c34b
3 changed files with 110 additions and 4 deletions
@@ -0,0 +1,100 @@
package com.adc.da.utils.removeHtml;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RemoveHtml {
/**
* 匹配html标签,例如"<p>xxx</p>"这种格式
*/
private static Pattern HTML_TAG_PATTERN = Pattern.compile("<[a-zA-Z]+.*?>([\\s\\S]*?)</[a-zA-Z]*?>");
/**
* 替换掉html标签里面的style内容
*
* @param content
* @return
*/
public static String replaceStyle(String content) {
if (content == null || content.length() == 0) {
return content;
}
String regEx = " style=\"(.*?)\"";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(content);
if (m.find()) {
content = m.replaceAll("");
}
return content;
}
/**
* 移除掉</br>标签
*
* @param src
* @return
*/
public static String removeBrTag(String src) {
if (src != null && !src.isEmpty()) {
src = src.replaceAll("<br/>", "");
}
return src;
}
/**
* 针对多个标签嵌套的情况进行处理
* 比如 <p><span style="white-space: normal;">王者荣耀</span></p>
* 预处理并且正则匹配完之后结果是 <span>王者荣耀
* 需要手工移除掉前面的起始标签
* @param content
* @return
*/
public static String replaceStartTag(String content) {
if (content == null || content.length() == 0) {
return content;
}
String regEx = "<[a-zA-Z]*?>([\\s\\S]*?)";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(content);
if (m.find()) {
content = m.replaceAll("");
}
return content;
}
/**
* 获取html中的数据
* @param htmlStr
* @return
*/
public static String getResultsFromHtml(String htmlStr) {
//定义script的正则表达式,去除js可以防止注入
String scriptRegex="<script[^>]*?>[\\s\\S]*?<\\/script>";
//定义style的正则表达式,去除style样式,防止css代码过多时只截取到css样式代码
String styleRegex="<style[^>]*?>[\\s\\S]*?<\\/style>";
//定义HTML标签的正则表达式,去除标签,只提取文字内容
String htmlRegex="<[^>]+>";
//定义空格,回车,换行符,制表符
String spaceRegex = "\\s*|\t|\r|\n";
// 过滤script标签
htmlStr = htmlStr.replaceAll(scriptRegex, "");
// 过滤style标签
htmlStr = htmlStr.replaceAll(styleRegex, "");
// 过滤html标签
htmlStr = htmlStr.replaceAll(htmlRegex, "");
// 过滤空格等
htmlStr = htmlStr.replaceAll(spaceRegex, "");
return htmlStr.trim(); // 返回文本字符串
}
}