.Net Regex to replace duplicate occurrences of a pattern with capture group
<p>I have a SQL script that goes something like this:</p>

<pre><code>DECLARE @MyVariable1 = 1
DECLARE @MyVariable1 = 10
DECLARE @MyVariable3 = 15
DECLARE @MyVariable2 = 20
DECLARE @MyVariable1 = 7
DECLARE @MyVariable2 = 4
DECLARE @MyVariable4 = 7
DECLARE @MyVariable2 = 4
</code></pre>

<p>Of course, the real script has lots of other stuff in the middle but I want to write a function that given the above input, outputs this:</p>

<pre><code>DECLARE @MyVariable1 = 1
@MyVariable1 = 10
DECLARE @MyVariable3 = 15
DECLARE @MyVariable2 = 20
@MyVariable1 = 7
@MyVariable2 = 4
DECLARE @MyVariable4 = 7
@MyVariable2 = 4
</code></pre>

<p>Essentially removing duplicate <code>DECLARE</code> statements for variables that have already been declared</p>

<p>My current solution is this:</p>

<pre><code>    Private Function RemoveDuplicateDeclarations(commandText As String) As String
        Dim lines = commandText.Split(New String() { vbCrLf }, StringSplitOptions.RemoveEmptyEntries)
        Dim declarationRegex As New Regex("(\r|\n|\r\n) *DECLARE *(?&lt;initialization&gt;(?&lt;varname&gt;[^ ]*) *.*)" &amp; vbCrLf , RegexOptions.Multiline Or RegexOptions.IgnoreCase)
        Dim declaredVariables As New List(Of String) 
        Dim resultBuilder As New StringBuilder()

        For Each line In lines    
            Dim matches = declarationRegex.Matches(line)
            If matches.Count &gt; 0 Then
                Dim varname = matches(0).Groups("varname").Value
                If declaredVariables.Contains(varname) Then
                    resultBuilder.AppendLine(declarationRegex.Replace(line, "${initialization}"))
                Else 
                    declaredVariables.Add(varname)

                    resultBuilder.AppendLine(line)
                End If
            Else
                resultBuilder.AppendLine(line)
            End If
        Next

        Return resultBuilder.ToString()
    End Function
</code></pre>

<p>It worked perfectly for my scripts (and there won't be any new scripts), but it seems a bit over complicated, since I can match the occurrences of what I want to replace I was wondering if there would be a way to just run <code>Regex.Replace()</code> with some arguments and accomplish that in one line</p>

<p>C# solutions welcome</p>

<p>-EDIT-</p>

<p>To clarify what I'm trying to achieve, I want an answer in the following format, or an explanation that it's impossible (modifying the regex is allowed).</p>

<pre><code>Private Function RemoveDuplicateDeclarations(commandText As String) As String
    Dim regex As New Regex("(\r|\n|\r\n) *DECLARE *(?&lt;initialization&gt;(?&lt;varname&gt;[^ ]*) *.*)" &amp; vbCrLf , RegexOptions.Multiline Or RegexOptions.IgnoreCase)
    Return regex.Replace(commandText, "What do I put here???????")
End Function
</code></pre>