Click here to Skip to main content
15,742,477 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
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();

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

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

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 ?
Updated 23-Dec-15 2:34am
W Balboos, GHB 23-Dec-15 8:44am    
When you have a "doesn't work" problem you should tell us what the "doesn't work" is; content of error message, if any; and what you do see.

Meanwhile - have you stepped through that part of the code in a debugger?
Have you considered that while HTML/CSS don't care about the number of spaces in a string, C# does?

dave_bulac 23-Dec-15 8:46am    
code donn't changes. It stays the same
Thomas Daniels 23-Dec-15 8:46am    
Please describe "not working". Do you get any errors, or unexpected output? In case of the latter, what's the input and how does the output look like?

1 solution

Try this:
public static Regex regex = new Regex(
      "(?<=<span class=\ \ \"nameLastname\ \ \">)(?<Name>.*)(?=</span>)",
    | RegexOptions.CultureInvariant
    | RegexOptions.Compiled
// This is the replacement string
public static string regexReplace = 
// 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]
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900