How do you reference a capture group with regex find and replace in Visual Studio 2012, 2013, 2015, and VS Code

Visual StudioVisual Studio-2012Visual Studio-2013Visual Studio-2015Visual Studio-Code

Visual Studio Problem Overview


I realize there are a ton of questions about this, but none that I found specifically referenced which VS version they referred to. With that important information lacking, I still was unable to successfully use the answers I found. The most common was

  • Surround with {}, display capture with \1, \2, \n

However, that seems to be the old method of doing regex find and replace in Visual Studio, and it does not work in VS 2012.

Visual Studio Solutions


Solution 1 - Visual Studio

To find and replace in VS 2012 and VS 2015 you do the following:

Example (thanks to syonip)

In the find options, make sure 'use regular expressions' is checked, and put the following as the text to find:

_platformActions.InstallApp\((.+)\)

And the following as the text to replace it with:

this.Platform().App($1).Install()

Note: As SLaks points out in a comment below, the change in regex syntax is due to VS2012 switching to the standard .Net regex engine.

Note: Another commenter pointed out that this works in Visual Studio Code (vscode) as well

Solution 2 - Visual Studio

To add an example of this, here is something I had to do in my code:

Find what:

_platformActions.InstallApp\((.+)\)

Replace with:

this.Platform().App($1).Install()

This replaces any call to InstallApp(x), with this.Platform().App(x).Install().

*Don't forget to mark "Use regular expressions" in Find options

Solution 3 - Visual Studio

If you want to work with using group names (using the same sample as above):

Find what:

_platformActions\.InstallApp\((?<mygroupname>.+)\)

Replace with:

this.Platform().App(${mygroupname}).Install()

Solution 4 - Visual Studio

To improve the above answers: You should replace

_platformActions.InstallApp\((.+)\)

with

this.Platform().App(${1}).Install()

Mind the ${1} if you ever want to add a number behind the capture. $18 will try to insert the 18th search capture, not the first with an 8 appended.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSgtPookiView Question on Stackoverflow
Solution 1 - Visual StudioSgtPookiView Answer on Stackoverflow
Solution 2 - Visual StudiosyonipView Answer on Stackoverflow
Solution 3 - Visual StudioYepeekaiView Answer on Stackoverflow
Solution 4 - Visual StudioLuc BloomView Answer on Stackoverflow