欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java过滤html标签获取纯文本信息的实例

程序员文章站 2023-12-15 08:16:46
如下所示: package com.lyt.base.util; import java.util.regex.pattern; public cla...

如下所示:

package com.lyt.base.util;

import java.util.regex.pattern;

public class filterhtmlutil {
public static string html2text(string inputstring){
  string htmlstr = inputstring; //含html标签的字符串
  string textstr ="";
  java.util.regex.pattern p_script;
  java.util.regex.matcher m_script;
  java.util.regex.pattern p_style;
  java.util.regex.matcher m_style;
  java.util.regex.pattern p_html;
  java.util.regex.matcher m_html;
  try{
     string regex_script = "<[\\s]*?script[^>]*?>[\\s\\s]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; //定义script的正则表达式{或<script[^>]*?>[\\s\\s]*?<\\/script> }
     string regex_style = "<[\\s]*?style[^>]*?>[\\s\\s]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; //定义style的正则表达式{或<style[^>]*?>[\\s\\s]*?<\\/style> }
     string regex_html = "<[^>]+>"; //定义html标签的正则表达式
     p_script = pattern.compile(regex_script,pattern.case_insensitive);
     m_script = p_script.matcher(htmlstr);
     htmlstr = m_script.replaceall(""); //过滤script标签
     p_style = pattern.compile(regex_style,pattern.case_insensitive);
     m_style = p_style.matcher(htmlstr);
     htmlstr = m_style.replaceall(""); //过滤style标签
     p_html = pattern.compile(regex_html,pattern.case_insensitive);
     m_html = p_html.matcher(htmlstr);
     htmlstr = m_html.replaceall(""); //过滤html标签
     textstr = htmlstr;
  }catch(exception e){
  e.printstacktrace();
  }
  return textstr;//返回文本字符串
} 
}

以上这篇java过滤html标签获取纯文本信息的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

上一篇:

下一篇: