c# 去除文本的html标签

本文介绍了一种使用正则表达式清理HTML标签和其他特殊字符的方法,通过一系列替换操作去除或转换了输入字符串中的HTML标签、换行符及特殊字符实体等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1 public static string ContentReplace(string input)
 2         {
 3             input = Regex.Replace(input, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
 4             input = Regex.Replace(input, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
 5             input = Regex.Replace(input, @"-->", "", RegexOptions.IgnoreCase);
 6             input = Regex.Replace(input, @"<!--.*", "", RegexOptions.IgnoreCase);
 7 
 8             input = Regex.Replace(input, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
 9             input = Regex.Replace(input, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
10             input = Regex.Replace(input, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
11             input = Regex.Replace(input, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
12             input = Regex.Replace(input, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
13             input = Regex.Replace(input, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
14             input = Regex.Replace(input, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
15             input = Regex.Replace(input, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
16             input = Regex.Replace(input, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
17             input = Regex.Replace(input, @"&#(\d+);", "", RegexOptions.IgnoreCase);
18 
19             input.Replace("<", "");
20             input.Replace(">", "");
21             input.Replace("\r\n", "");
22             //去两端空格,中间多余空格
23             input = Regex.Replace(input.Trim(), "\\s+", " ");
24             return input;
25         }

 

转载于:https://www.cnblogs.com/ghelement/p/4511499.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值