使用正则表达式写的清除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>[/r/n//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(), "[/u0020]+", "/u0020", options); // 替换多个连续空格
      else
        return txt;
    }

    private static string Html2Text_Match(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 "/xa1";
      else if (m.Groups["cent"].Value != string.Empty)
        return "/xa2";
      else if (m.Groups["pound"].Value != string.Empty)
        return "/xa3";
      else if (m.Groups["copy"].Value != string.Empty)
        return "(c)";
      else if (m.Groups["space"].Value != string.Empty)
        return "/u0020";
      else if (m.Groups["control"].Value != string.Empty)
        return "/u0020";
      else
        return string.Empty;
    }
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值