正则如何替换字符串

wgale025 2010-06-01 06:38:45

string html = "<html><head><title>asp.net</title></head><body>百度<img src='b.jpg' alt='百度' 各title='百度' /></body></html>";

string href = "<a href='http://www.baidu.com/' title='百度'>百度</a>";


我想把html里面的“百度”两个字替换成href变量中的内容,但是我不想替换,img中的alt和title属性中的百度关键字,我该怎么做呢?
...全文
59 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
wgale025 2010-06-02
  • 打赏
  • 举报
回复
我自己解决了。不过你的办法不错,居然可以用匿名委托的方式使用正则表达式,又学了一招。

string html = "<html><head><title>asp.net</title></head><body>百度<img src='b.jpg' alt=\"百度\" />百度什么呀百度好强呀百度小心呀</body></html>";
string key = "百度";
string href = "<a href='http://www.baidu.com/' title='百度'>百度</a>";
Console.WriteLine(Regex.Replace(html, "([^='\"]?)("+key+")([^='\"])", "$1"+href+"$3", RegexOptions.IgnoreCase));

-过客- 2010-06-01
  • 打赏
  • 举报
回复
try...

string html = "<html><head><title>asp.net</title></head><body>百度<img src='b.jpg' alt='百度' 各title='百度' /></body></html>";
string key = "百度";
string href = "<a href='http://www.baidu.com/' title='百度'>百度</a>";
Regex reg = new Regex(@"(^|>)[^<>]+(<|$)");
string result = reg.Replace(html, delegate(Match m) { return m.Value.Replace(key, href); });
richTextBox2.Text = result;
-过客- 2010-06-01
  • 打赏
  • 举报
回复
try...

string html = "<html><head><title>asp.net</title></head><body>百度<img src='b.jpg' alt='百度' 各title='百度' /></body></html>";
string key = "百度";
string href = "<a href='http://www.baidu.com/' title='百度'>百度</a>";
Regex reg = new Regex(@"(^|>)[^<>]+(<|$)");
string result = reg.Replace(html, delegate(Match m) { return m.Value.Replace(key, href); });
richTextBox2.Text = result;
wgale025 2010-06-01
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 ccs02287 的回复:]
查找、替换
[/Quote]
汗,我要用程序替换。最后生成的代码是:
"<html><head><title>asp.net</title></head><body><a href='http://www.baidu.com/' title='百度'>百度</a><img src='b.jpg' alt='百度' 各title='百度' /></body></html>"

这个是我最后要的结果,通过编程实现。
空心兜兜 2010-06-01
  • 打赏
  • 举报
回复
查找、替换

62,046

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧