java代码如何剔除字符串中的html标签呢?

欣喜 Java经验 发布时间:2024-02-01 15:23:42 阅读数:18532 1
下文笔者讲述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;
    }
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202402/17067722827873.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者