java如何去掉字符串中的 html标签

Python013

java如何去掉字符串中的 html标签,第1张

1.去除单个HTML标记

String s="asdfasd<script>asdfsfd</script>1234"

System.out.println(s.replaceAll("<script.*?(?<=/script>)",""))

2.去除所有HTML标记

import java.util.regex.Matcher

import java.util.regex.Pattern

public class HTMLSpirit{ ITjob 远标教育

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()//返回文本字符串

}

}

是因为在JSP页面使用struts或者jstl标签,最终jsp页面都会转化成java代码来执行的,所有的输出都会转化成response.getWriter().write(String)。

response.getWriter().write(“<span>你好</span>”)。这样就会向前台输出<span>你好</span>,如果是标签的话,首先处理标签把标签转化成对应的字符串,最终还是以response.getWriter().write(String)方式输出的页面。如果你有了解自定义标签,你就理解这些标签是如何输出的了。

可以通过replaceAll方法进行字符串替换,之后替换的内容用正则表达式来匹配。举例

String ss="<div id='mini_nav_qq'><li><a target='_top' " +

  "href='http:// lady.qq.com/emo/emotio.shtml'>情感</a></li><li>" +

  "<a target='_top' href='http://lady.qq.com/beauty/beauty.shtml'>美容</a></li></div>"

String ss=ss.replaceAll("<(/?\\S+)\\s*?[^<]*?(/?)>","<$1$2>")//通过只保留"<“后面的字符串,之后删除空格和后面的内容,快捷的实现去除操作(此方法通用于所有的标签去除,只需要传入不同的ss值)。

结果就是:<div><li><a>情感</a></li><li><a>美容</a></li></div>。