java使用正则表达式去除字符串的html标签

 http://www.javaeye.com/topic/217508

新闻内容或者博客文章,如果显示摘要,需要去除内容的html格式标签,找到一个正则表达式,实现了:

 

代码
/**
     * 删除input字符串中的html格式
     * 
     *  @param  input
     *  @param  length
     *  @return
     
*/
    
public   static  String splitAndFilterString(String input,  int  length) {
        
if  (input  ==   null   ||  input.trim().equals( "" )) {
            
return   "" ;
        }
        
//  去掉所有html元素,
        String str  =  input.replaceAll( " \\&[a-zA-Z]{1,10}; " "" ).replaceAll(
                
" <[^>]*> " "" );
        str  =  str.replaceAll( " [(/>)<] " "" );
        
int  len  =  str.length();
        
if  (len  <=  length) {
            
return  str;
        }  else  {
            str  =  str.substring( 0 , length);
            str  +=   " ...... " ;
        }
        
return  str;
    }

其中:

\\&代表 &字符 ,而[a-zA-Z]{1,10} 代表任意字母(包含大小写)组成的字串,长度为1到10 ,这样的表达式用来匹配例如:&lt; &gt; &nbsp; 之类的字串 。

 

原帖的另一回帖:

方法明显太过暴力,假如我的内容用<1><2><3>这样的形式来作为步骤的标示,那不是一样被删。


//  去掉所有html元 素,     
String str  =  input.replaceAll( " <[a-zA-Z]+[1-9]?[^><]*> " "" )  
                  .replaceAll(
" </[a-zA-Z]+[1-9]?> " "" );  


 

你可能感兴趣的:(html标签)