title: Regex if match then replace
body: <p>I've looked around to try to find an answer to this question, but I can't find exactly what I'm looking for.  It seems like there should be a way to decide if there is a match and replace, otherwise do something else without the need to repeat the matching.</p>
  
  <p>I'm trying to decide if the test string contains an HTML document that ends in </p>
  
  <pre><code>&lt;/body&gt;&lt;/html&gt;
  </code></pre>
  
  <p>and inject some text directly ahead of those tags.  Of course there might be a combination of white-space/carriage-returns/line-feeds between the 2 tags, thus I'm trying this with Regex.  However, the test string might be just plain text and if the Regex match fails, I will just append the text to the end of the string.  And of course, I'm probably making this more difficult than it really is.</p>
  
  <p>I don't really have any code to show here since I can't figure out if this is possible with .NET Regex implementation, but here is some psudo-code showing what I would like to do:</p>
  
  <pre><code>        Dim testString As String = some file contents
          Dim reg As New Regex("(&lt;\/body&gt;\s*&lt;\/html&gt;)", RegexOptions.IgnoreCase)
          Dim rMatch As Match = reg.Match(testString)
          If rMatch.Success Then
              rMatch.Replace(newString)
          Else
              testString &amp;= alternateNewString
          End If
  </code></pre>
  
  <p>Of course I would need to put the end body and end html tags into the newString to properly close the document, but that should be no problem.  The part I can't seem to implement is the match replacement without the need to run the regex again.  It seems like calling match to determine if it is a match, then calling replace is making it run twice.  And again, I might be over thinking this, or prematurely optimizing.  What do you think? </p>