我们写完一篇文章,会在文章中截取前面一串文字用来在列表显示,但是因为是用富文本编辑的,所以也会含有html标签,如果直接在页面列表展示,会影响页面布局,如果直接纯文本展示,会展示出html标签。
这里有一个工具类可以很方便的去除掉字符串中的html标签,如下:
public class Html2Text extends HTMLEditorKit.ParserCallback{private static Html2Text h2t = new Html2Text();private Html2Text(){};private StringBuffer s;private void parse(String str) throws IOException {InputStream iin = new ByteArrayInputStream(str.getBytes());Reader in = new InputStreamReader(iin);s = new StringBuffer();ParserDelegator delegator = new ParserDelegator();// the third parameter is TRUE to ignore charset directivedelegator.parse(in, this, Boolean.TRUE);iin.close();in.close();}public void handleText(char[] text, int pos) {s.append(text);}public String getText() {return s.toString();}public static String getContent(String str) {try {h2t.parse(str);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return h2t.getText();}public static void main (String[] args) {System.out.println(Html2Text.getContent("<p>这里介绍PYTHON的头文件含义<br>1、第一行<br> 脚本语言的第一行,目的就是指出,你想要你的这个文件中的代码用什么可执行程序去运行它,就这么简单。</p>\n" +"<pre class=\"prettyprint linenums prettyprinted\" style=\"\"><ol class=\"linenums\"><li class=\"L0\"><code><span class=\"co"));}}
运行后结果如下:

可以看到,标签都被过滤啦,再也不用正则表达式来替换。
