Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Regex Replace using match value

Tags:

c#

regex

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;
}
like image 637
user1573618 Avatar asked Oct 23 '25 19:10

user1573618


2 Answers

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.

like image 171
Seth Flowers Avatar answered Oct 26 '25 08:10

Seth Flowers


You are not reallocating to html

so:

html = html.Replace(ItemMatch.Value, "<h2>My Partial View</h2>"); 
like image 45
Chris Avatar answered Oct 26 '25 09:10

Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!