Reputation: 1816
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;
}
Upvotes: 4
Views: 10110
Reputation: 9210
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.
Upvotes: 7
Reputation: 22064
How about this? That way you are using the value from the match to replace with?
The biggest issue however was that you weren't reassigning the result of the replace to the html variable.
using System;
using System.Text.RegularExpressions;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var html = @"
<h1>This is a Title</h1>
@Html.Partial(""MyPartialView"")
";
var itemRegex = new Regex(@"@Html.Partial\(""([a-zA-Z]+)""\)", RegexOptions.Compiled);
html = itemRegex.Replace(html, "<h2>$1</h2>");
Console.WriteLine(html);
Console.ReadKey();
}
}
}
Upvotes: 0
Reputation: 14521
As the other answers state, you are not assigning the resulting value.
I would add, that your foreach cycle doesn't make much sense and you could go with inline replace:
Regex ItemRegex = new Regex(@"@Html.Partial\(""[a-zA-Z]+""\)", RegexOptions.Compiled);
html = ItemRegex.Replace(html, "<h2>My Partial View</h2>");
Upvotes: 0
Reputation: 1816
Feeling very silly. The string is ummutable so I need to recreate it.
html = html.Replace(ItemMatch.Value, "<h2>My Partial View</h2>");
Upvotes: -1
Reputation: 2481
You are not reallocating to html
so:
html = html.Replace(ItemMatch.Value, "<h2>My Partial View</h2>");
Upvotes: 1