I'm using a regex to replace values within some html code. It correctly matches all instances within the html code but when using Regex.Replace() with back references it doesn't replace the back references.
For example
html = "<td>[element]elementreference='oldvalue';[/element]</td>";
html = Regex.Replace(html, @"(['""#(=])" + elementReference.Key + @"(['""#)];|&)", "$1" + elementReference.Value + "$2", RegexOptions.IgnoreCase);
results in:
"<td>[element]elementreference=$1newvalue'[/element]</td>"
but if I use
html = "<td>[element]elementreference='oldvalue';[/element]</td>";
var regex = new Regex(@"(['""#(=])" + elementReference.Key + @"(['""#)];|&)", RegexOptions.IgnoreCase);
foreach (Match match in regex.Matches(html))
{
html = html.Replace(match.Value, match.Groups[1] + elementReference.Value + match.Groups[2]);
}
the result is
"<td>[element]elementreference='newvalue'[/element]</td>"
which is what I expected.
Can anyone explain why using Regex.Replace() did not work?
EDIT
I am not attempting to replace the inner html, I am attempting to replace the 'oldvalue'
part of [element]elementreference='oldvalue'[/element]
, which just happens to be in a html tag. My problem lies with the fact that I am trying to replace the apostrophe around the text, by using a back reference. This apostrophe could be a number of values, that is why I am using a back reference.