Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can work with groups in a regex. You create groups by using parentheses in your regular expression. When you get a <code>Match</code> object, this object will contain a <code>Group</code> collection: </p> <pre><code>string input = "&lt;html&gt;&lt;img id=\"someImage\" src=\"C:\\logo.png\" height=\"64\" width=\"104\" alt=\"myImage\" /&gt;&lt;/html&gt;"; var regex = new Regex("(&lt;img(.+?)id=\"someImage\"(.+?))src=\"([^\"]+)\""); string output = regex.Replace( input, match =&gt; match.Groups[1].Value + "src=\"someothervalue\"" ); </code></pre> <p>In the example above there will be 5 groups:</p> <ul> <li><code>Groups[0]</code> This is the whole match: <code>&lt;img id=\"someImage\" src=\"C:\\logo.png\"</code></li> <li><code>Groups[1]</code> This is everything before the <code>src</code> attribute: <code>&lt;img id=\"someImage\" </code></li> <li><code>Groups[2]</code> and <code>Groups[3]</code> are the <code>(.+?)</code> parts.</li> <li><code>Groups[4]</code> is the original value of the <code>src</code> attribute: <code>C:\logo.png</code></li> </ul> <p>In the example I replace the whole match for the value of <code>Groups[1]</code> and a new src attribute.</p> <p><strong>Footnote</strong>: While regular expressions can sometimes be adequate for the job to manipulate an html document, it is often not the best way. If you know in advance that you are working with <code>xhtml</code>, then you can use <code>XmlDocument</code> + <code>XPath</code>. If it is html, then you can use <a href="http://htmlagilitypack.codeplex.com/" rel="nofollow">HtmlAgilityPack</a>.</p>
 

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