Note that there are some explanatory texts on larger screens.

plurals
  1. PORegex back references in Regex.Replace()
    primarykey
    data
    text
    <p>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.</p> <p>For example</p> <pre><code>html = "&lt;td&gt;[element]elementreference='oldvalue';[/element]&lt;/td&gt;"; html = Regex.Replace(html, @"(['""#(=])" + elementReference.Key + @"(['""#)];|&amp;)", "$1" + elementReference.Value + "$2", RegexOptions.IgnoreCase); </code></pre> <p>results in: </p> <pre><code>"&lt;td&gt;[element]elementreference=$1newvalue'[/element]&lt;/td&gt;" </code></pre> <p>but if I use</p> <pre><code>html = "&lt;td&gt;[element]elementreference='oldvalue';[/element]&lt;/td&gt;"; var regex = new Regex(@"(['""#(=])" + elementReference.Key + @"(['""#)];|&amp;)", RegexOptions.IgnoreCase); foreach (Match match in regex.Matches(html)) { html = html.Replace(match.Value, match.Groups[1] + elementReference.Value + match.Groups[2]); } </code></pre> <p>the result is </p> <pre><code>"&lt;td&gt;[element]elementreference='newvalue'[/element]&lt;/td&gt;" </code></pre> <p>which is what I expected.</p> <p>Can anyone explain why using Regex.Replace() did not work?</p> <p><strong>EDIT</strong></p> <p>I am not attempting to replace the inner html, I am attempting to replace the <code>'oldvalue'</code> part of <code>[element]elementreference='oldvalue'[/element]</code>, 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.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload