I am trying to write a function in C# to replace all occurances of a regex pattern with a custom string. I need to use the match string to generate the replace string so I am trying to loop over the matches rather than use Regex.Replace(). When I debug my code, the regex pattern matches part of my html string and goes into the foreach loop, however, the string.Replace function doesn't replace the match. Does anyone know what is causing this to happen?
Simplified version of my function:-
public static string GetHTML() {
string html = @"
<h1>This is a Title</h1>
@Html.Partial(""MyPartialView"")
";
Regex ItemRegex = new Regex(@"@Html.Partial\(""[a-zA-Z]+""\)", RegexOptions.Compiled);
foreach (Match ItemMatch in ItemRegex.Matches(html))
{
html.Replace(ItemMatch.Value, "<h2>My Partial View</h2>");
}
return html;
}
stringobjects are immutable, to further explain @sethflowers answer.Compiledoption? You should use that only when you have a demonstrated need for it. The performance boost it offers is not that great, and it does not come for free. ref