在网页刚流行起来的时候,提取html中的文本有一个简单的方法,就是将html文本(包含标记)中的所有以符号开头到以符号之间的内容去掉即可。
但对于现在复杂的网页而言,用这种方法提取出来的文本会有大量的空格、空行、script段落、还有一些html转义字符,效果很差。
下面用正则表达式来提取html中的文本,
代码的实现的思路是:
a、先将html文本中的所有空格、换行符去掉(因为html中的空格和换行是被忽略的)
b、将标记中的所有内容去掉
c、将
d、将
e、将td换成空格,tr,li,br,p等标记换成换行符
f、去掉所有以符号为头尾的标记去掉。
g、转换amp;,nbps;等转义字符换成相应的符号
h、去掉多余的空格和空行
代码如下:
usingSystem;
usingSystem.Text.RegularExpressions;
namespaceKwanhong.Utilities
{
///summary
///HtmlToText的摘要说明。
////summary
publicclassHtmlToText
{
publicstringConvert(stringsource)
{
stringresult;
//removelinebreaks,tabs
result=source.Replace(\r,);
result=result.Replace(\n,);
result=result.Replace(\t,);
//removetheheader
result=Regex.Replace(result,(head).*(/head),string.Empty,RegexOptions.IgnoreCase);
result=Regex.Replace(result,@()*script([^])*,script,RegexOptions.IgnoreCase);
result=Regex.Replace(result,@(script).*(/script),string.Empty,RegexOptions.IgnoreCase);
//removeallstyles
result=Regex.Replace(result,@()*style([^])*,style,RegexOptions.IgnoreCase);//clearingattributes
result=Regex.Replace(result,(style).*(/style),string.Empty,RegexOptions.IgnoreCase);
//inserttabsinspacesoftdtags
result=Regex.Replace(result,@()*td([^])*,,RegexOptions.IgnoreCase);
//insertlinebreaksinplacesofbrandlitags
result=Regex.Replace(result,@()*br()*,\r,RegexOptions.IgnoreCase);
result=Regex.Replace(result,@()*li()*,\r,RegexOptions.IgnoreCase);
//insertlineparagraphsinplacesoftrandptags
result=Regex.Replace(result,@()*tr([^])*,\r\r,RegexOptions.IgnoreCase);
result=Regex.Replace(result,@()*p([^])*,\r\r,RegexOptions.IgnoreCase);
//removeanythingthatsenclosedinside
result=Regex.Replace(result,@[^]*,string.Empty,RegexOptions.IgnoreCase);
//replacespecialcharacters:
result=Regex.Replace(result,@amp;,,RegexOptions.IgnoreCase);
result=Regex.Replace(result,@nbsp;,,RegexOptions.IgnoreCase);
result=Regex.Replace(result,@lt;,,RegexOptions.IgnoreCase);
result=Regex.Replace(result,@gt;,,RegexOptions.IgnoreCase);
result=Regex.Replace(result,@(.{2,6});,string.Empty,RegexOptions.IgnoreCase);
//removeextralinebreaksandtabs
result=Regex.Replace(result,@()+,);
result=Regex.Replace(result,(\r)()+(\r),\r\r);
result=Regex.Replace(result,@(\r\r)+,\r\n);
returnresult;
}
}//endclass
}//endnamespace
0 评论:
发表评论