把html源代码变为text的方法

本文介绍了一款实用工具——HTML至纯文本转换器。该工具通过正则表达式匹配和替换HTML标签及特殊字符,将HTML内容转换为纯文本格式,并支持保留或去除换行格式。
 
        //------------
        private static string html2TextPattern =  
            
@"(?<script><script[^>]*?>.*?</script>)|(?<style><style>.*?</style>)|(?<comment><!--.*?-->)" + 
            
@"|(?<html><[^>]+>)" + // HTML标记 
            @"|(?<quot>&(quot|#34);)" + // 符号: " 
            @"|(?<amp>&(amp|#38);)" + // 符号: & 
            @"|(?<lt>&(lt|#60);)" + // 符号: < 
            @"|(?<gt>&(gt|#62);)" + // 符号: > 
            @"|(?<iexcl>&(iexcl|#161);)" + // 符号: (char)161 
            @"|(?<cent>&(cent|#162);)" + // 符号: (char)162 
            @"|(?<pound>&(pound|#163);)" + // 符号: (char)163 
            @"|(?<copy>&(copy|#169);)" + // 符号: (char)169 
            @"|(?<others>&(d+);)" + // 符号: 其他 
            @"|(?<space>&nbsp;|&#160;)"// 空格 

        
/// <summary> 
        
/// 转换HTML为纯文本 
        
/// </summary> 
        
/// <param name="html">HTML字符串</param> 
        
/// <param name="keepFormat">是否保留换行格式</param> 
        
/// <returns></returns> 

        public static string Html2Text(string html, bool keepFormat) 
        

            
string pattern = html2TextPattern; 
            
if (! keepFormat) pattern += "|(?<control>[ /s])"// 换行字符 

            RegexOptions options 
= RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Compiled; 
            
string txt = Regex.Replace(html, pattern, new MatchEvaluator(Html2Text_Match), options); 

            
if (! keepFormat) 
                
return Regex.Replace(txt.Trim(), "[ ]+"" ", options); // 替换多个连续空格 
            else 
                
return txt; 
        }
 

        
private static string Html2Text_Match(System.Text.RegularExpressions.Match m) 
        

            
if (m.Groups["quot"].Value != string.Empty) 
                
return """
            
else if (m.Groups["amp"].Value != string.Empty) 
                
return "&"
            
else if (m.Groups["lt"].Value != string.Empty) 
                
return "<"
            
else if (m.Groups["gt"].Value != string.Empty) 
                
return ">"
            
else if (m.Groups["iexcl"].Value != string.Empty) 
                
return "¡"
            
else if (m.Groups["cent"].Value != string.Empty) 
                
return "¢"
            
else if (m.Groups["pound"].Value != string.Empty) 
                
return "£"
            
else if (m.Groups["copy"].Value != string.Empty) 
                
return "(c)"
            
else if (m.Groups["space"].Value != string.Empty) 
                
return " "
            
else if (m.Groups["control"].Value != string.Empty) 
                
return " "
            
else 
                
return string.Empty; 
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值