正则表达式 去除相应HTML 标记

将HTML文本中的标记分为:注释,script ,style,以及其他标记分别去掉:

       1.去注释,正则为:

          output = Regex.Replace(input, @"<!--[^-]*-->", string.Empty, RegexOptions.IgnoreCase);

      2.去script,正则为:

          ouput = Regex.Replace(input, @"<script[^>]*?>.*?</script>", string.Empty, RegexOptions.IgnoreCase | RegexOptions.Singleline);
           output2 = Regex.Replace(ouput , @"<noscript[^>]*?>.*?</noscript>", string.Empty, RegexOptions.IgnoreCase | RegexOptions.Singleline);

       3.去style,正则为:

         output = Regex.Replace(input, @"<style[^>]*?>.*?</style>", string.Empty, RegexOptions.IgnoreCase | RegexOptions.Singleline);

       4.去其他HTML标记

         result = result.Replace("&nbsp;", " ");
          result = result.Replace("&quot;", "\"");
         result = result.Replace("&lt;", "<");
          result = result.Replace("&gt;", ">");
          result = result.Replace("&amp", "&");
          result = result.Replace("<br>", "\r\n");
          result = Regex.Replace(result, @"<[\s\S]*?>", string.Empty, RegexOptions.IgnoreCase);

      以上的代码中大家可以看到,我使用了RegexOptions.Singleline参数,这个参数很重要,他主要是为了让"."(小圆点)可以匹配换行符.如果没有这个参数,大多数情况下,用上面列正则表达式来消除网页HTML标记是无效的.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值