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;
}
string.Replace returns a string value. You need to assign this to your html variable. Note, also that it replaces all occurrences of the matched value, meaning you likely don't need your loop.
html = html.Replace(ItemMatch.Value, "<h2>My Partial View</h2>");
Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.
You are not reallocating to html
so:
html = html.Replace(ItemMatch.Value, "<h2>My Partial View</h2>");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With