使用c#替换html中的标签范围之间的文本 [英] Replace text between tags span in html with c#

查看:366
本文介绍了使用c#替换html中的标签范围之间的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好。我正在使用Windows窗体中的项目,我需要在html文档中的标签之间替换文本。我写了以下代码:

Hello guys. I am working on my Project in Windows Forms and I need to replace text between tags span in html Document. I have following Code written:

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();



我想替换例如< span class =nameLastname> George< / span> width< span class =nameLastname> Dave< / span> 。但我的代码不起作用。任何人都可以帮我吗?


I want to Replace for example "<span class="nameLastname">George</span>" width "<span class="nameLastname">Dave</span>" . But my code donn't work. Can anyone Help me with it ?

推荐答案

试试这个:

Try this:
public static Regex regex = new Regex(
      "(?<=<span class=\ \ \"nameLastname\ \ \">)(?<Name>.*)(?=</span>)",
    RegexOptions.Singleline
    | RegexOptions.CultureInvariant
    | RegexOptions.Compiled
    );
// This is the replacement string
public static string regexReplace = 
      "Dave";
// Replace the matched text in the InputText using the replacement pattern
string result = regex.Replace(InputText,regexReplace);







[edit]Remove the spaces between the backslashes - otherwise Markdown swallows parts of the regex...[/edit]


这篇关于使用c#替换html中的标签范围之间的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆