Search code examples
regexreplacesql-server-2008-r2ssmscapturing-group

Find and replace using regular expression, group capturing, and back referencing


I'm trying to perform a find and replace operation in SQL Server 2008 R2 Management Studio and employ a group capture so that I can back reference the groups in the replacement. I understand from this that SSMS uses the Visual Studio 2005 regex engine. Here is an example of what I have:

SELECT First FROM Table1
SELECT Second FROM Table2
SELECT Third FROM Table3

Here is my "Find" expression:

SELECT (.+) FROM (.+)

Here is my "Replace" expression:

\1 \2

However, running the replace operation results in no captured groups being returned, i.e. each line is just " " (<---just the space between the two back-references).

What am I doing wrong?


Solution

  • SQL Server Management Studio engine uses { and } to "tag" expressions:

    SELECT {.+} FROM {.+}
    

    When you combine this with the \1 \2 replacement expression, you get the expected result:

    First Table1
    Second Table2
    Third Table3
    

    VS Regex reference page explains the details.