SgtPooki
SgtPooki

Reputation: 11679

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

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

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.

Upvotes: 356

Views: 142765

Answers (5)

Damir Nafikov
Damir Nafikov

Reputation: 332

In VSCode v(1.61.1) in Ubuntu
I have to place (*someExpression*) in like $1
So the moment is I wasn't need to use extra brackets like ($1)

Upvotes: 2

Yepeekai
Yepeekai

Reputation: 2723

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()

Upvotes: 19

Luc Bloom
Luc Bloom

Reputation: 1253

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.

Upvotes: 17

SgtPooki
SgtPooki

Reputation: 11679

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

Upvotes: 473

syonip
syonip

Reputation: 2971

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

Upvotes: 21

Related Questions