【问题标题】:Replace text between tags span in html with c#用c#替换html中标签span之间的文本
【发布时间】:2016-03-29 22:44:51
【问题描述】:

我需要替换 HTML 文档中 <span> 标记之间的文本。我有以下代码:

string pattern = "<span class=\"nameLastname\">(.*)</span>";
string nameLastnamePattern = "<span class=\"nameLastname\">"+name+ lastname+"</span>";

System.IO.StreamReader objReader;
objReader = new StreamReader(System.IO.Directory.GetCurrentDirectory() + "\\intel\\main.html");
string content = objReader.ReadToEnd();
objReader.Close();

content = Regex.Replace(content,pattern, nameLastnamePattern);

StreamWriter writer = new StreamWriter(System.IO.Directory.GetCurrentDirectory() + "\\intel\\main.html");
writer.Write(content);
writer.Close();

例如,我想将&lt;span class="nameLastname"&gt;George&lt;/span&gt; 替换为&lt;span class="nameLastname"&gt;Dave&lt;/span&gt;。但是我的代码不起作用。

【问题讨论】:

  • Regex 和 Html 不能很好地配合使用。 Html Agility Pack 是你的朋友,htmlagilitypack.codeplex.com
  • 我认为您的模式除了“之外还包含更多正则表达式特定字符。我总是使用 Notepad++ 查找/替换功能来快速验证正则表达式模式。尝试 "([A -Za-z ]*)"
  • 您也可以使用在线测试仪。 regexstorm.net/testerregexhero.net/tester

标签: c# .net regex


【解决方案1】:

Working example on Rextester.

模式:@"&lt;span([^&gt;]*)class=\""(\w+)\""([^&gt;]*)&gt;(.*)&lt;\/span&gt;"

Regex regex = new Regex(pattern, RegexOptions.Multiline);
regex.Replace (inputData, "<span${1}class=\"${2}\"${3}>Replacement</span>")

第一组在class 属性之前捕获内容。第二组捕获类名。第三组捕获 类之后的属性。第四组是实际的跨度节点元素内容。被替换了。

【讨论】:

  • 在模式中,当我想替换 class=lastname 的跨度时。我应该写什么? @"]*)class=\""姓\""([^>]*)>(.*)" ?
  • 我想更改 Html 文档中的用户数据,例如姓名、姓氏、手机、年龄。 .例如:年龄在 Age 中。移动位于 231231。对他们来说,Pattern 会怎样?
  • 答案就在其中。第二组捕获类名。你可以通过它来切换。顺便说一句,这是一个新问题...
  • 所以当我想替换姓氏的值时,我必须写: Regex regex = new Regex(pattern, RegexOptions.Multiline); regex.Replace (inputData, ""+324123123+"") ?
猜你喜欢
  • 1970-01-01
  • 2013-09-05
  • 2017-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多