java代码如何剔除字符串中的html标签呢?
下文笔者讲述java代码剔除字符串中html标签的方法及示例分享,如下所示
我们只需使用正则表达式 剔除左右尖括号 的方式实现删除字符串中html标签的效果例
//方式1 使用正则表达式剔除左右尖括号 String htmlStr="html代码"; htmlStr = htmlStr.replaceAll("<[.[^<]]*>", ""); //方式2:使用正则表达式替换html类似的标签 //标题去掉样式 空格 private static Pattern FilePattern = Pattern.compile("[\\\\/:*?\"<>|]"); public static String filenameFilter(String htmlStr) { String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式 String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式 String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式 Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE); Matcher m_script = p_script.matcher(htmlStr); htmlStr = m_script.replaceAll(""); // 过滤script标签 Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE); Matcher m_style = p_style.matcher(htmlStr); htmlStr = m_style.replaceAll(""); // 过滤style标签 Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE); Matcher m_html = p_html.matcher(htmlStr); htmlStr = m_html.replaceAll(""); // 过滤html标签 String str = htmlStr.trim(); // 返回文本字符串 str = str == null ? null : FilePattern.matcher(str).replaceAll(""); str = str.replaceAll("\\s*", "").replaceAll("", ""); return str; }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。