Java去掉html标签

文章介绍了如何使用Java的正则表达式去掉HTML标签,包括script、style及普通HTML标签。示例代码展示了replaceAll方法的应用,并提到了特殊情况如换行的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java去掉html标签

<span style="font-family: 宋体; font-size: 10.5pt;"><o:p></o:p></span></p><p class="MsoNormal" style="margin: 0pt 0pt 0.0001pt; text-align: justify; font-family: Calibri; font-size: 10.5pt; text-indent: 21pt; line-height: 21px;"><span style="font-family: 宋体; font-size: 10.5pt;">欢迎咨询、合作!</span><span style="font-family: 宋体; font-size: 10.5pt;"><o:p></o:p></span></p>

像去掉这种标签可以使用正则:

public static String delHTMLTag(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标签 

        return htmlStr.trim(); //返回文本字符串 
    } 

也可以使用Java的String方法的replaceAll()方法:

String string = "<span style="font-family: 宋体; font-size: 10.5pt;"><o:p></o:p></span></p><p class="MsoNormal" style="margin: 0pt 0pt 0.0001pt; text-align: justify; font-family: Calibri; font-size: 10.5pt; text-indent: 21pt; line-height: 21px;"><span style="font-family: 宋体; font-size: 10.5pt;">欢迎咨询、合作!</span><span style="font-family: 宋体; font-size: 10.5pt;"><o:p></o:p></span></p>"
string=string.replaceAll("\\<.*?>",  "");//去掉所有的标签
string=string.replaceAll("&nbsp;",  "");//去掉前端的空格
System.out.println(string);

如有特殊的需求,比如换行之类的可以添加以下内容:

// <p>段落替换为换行 
content = content.replaceAll("<p .*?>", "\r\n"); 
// <br><br/>替换为换行 
content = content.replaceAll("<br\\s*/?>", "\r\n");

来看最终的效果:
在这里插入图片描述

结束!!!又是继续摸鱼的一天。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值