c#处理html字符串
来源:互联网 发布:在英国怎么用淘宝网 编辑:程序博客网 时间:2024/05/21 06:45
最近碰到个问题,html encode后的字符串,需要替换里面的文本内容。需要注意的地方是标签里面的内容不能被替换。
比如<p>pdf</p>,替换p为abc的时候<p>,</p>里面的p不能被替换。
纠结了很久终于解决:
1. 利用System.Web里的HttpUtility.HtmlDecode将字符串解码,比如<>会被解码成<>
2. 利用正则表达式隔离tag和tag外的内容Regex reg = new Regex("(<[a-zA-z/][^>]*>)");
3. 隔开后的string总在一个string 的list中,在通过判断是不是<>开头结尾来过滤,不是标签的话就替换内容
代码如下
private static void replaceText(string text,ref List<string> ll)
{
string html = HttpUtility.HtmlDecode(text);
Regex reg = new Regex("(<[a-zA-z/][^>]*>)");
Match mm = reg.Match(html);
string temp = string.Empty;
if (mm.Groups.Count > 1)
{
Group gg = mm.Groups[1];
ll.Add(html.Substring(0,gg.Index));
ll.Add(html.Substring(gg.Index,gg.Length));
replaceText(html.Substring(gg.Index + gg.Length), ref ll);
}
else
ll.Add(text);
}
static void Main(string[] args)
{
List<string> ll = new List<string>();
replaceText("pvc<p src=/"ds/">dpp</p><p>spdf<br /></p><a href=/"wwwp />fgdfgp",ref ll);
string result = string.Empty;
for(int i =0;i<ll.Count;i++)
{
string s = ll[i];
if((!string.IsNullOrEmpty(s))&& !(s.StartsWith("<")&&s.EndsWith(">")))
s = s.Replace("p","替换");
Console.WriteLine(s);
result += s;
}
Console.WriteLine("result: " +result);
}
- c#处理html字符串
- html字符串处理
- php处理html字符串
- C#中的字符串处理
- C# 处理字符串
- C#字符串处理类
- C#字符串处理类
- C#字符串处理类
- C#字符串处理类
- C#字符串处理类
- C#字符串处理(@)
- C#字符串处理
- C#字符串处理
- C#字符串处理
- C#字符串处理类
- C# 字符串处理方法
- C#字符串处理
- C#字符串处理
- (最大流) POJ 1698 Alice's Chance
- MySQL中把一个查询结果插入到另外一个表中
- 网址
- jQuery Autocomplete
- C#如何为winform程序打包发布应用(图解教程)
- c#处理html字符串
- 电脑不中毒的七点高招
- C#多线程学习(五) 多线程的自动管理(定时器) (转载)
- HTTP长连接服务器端推技术
- 光的物理属性
- GCC和GDB常用参数
- printk的那点事
- (最大流-简单题) poj 1273 Drainage Ditches
- VC++ UDP实现可靠传输(文件) UDX协义