Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

  • 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.

like image 267
SgtPooki Avatar asked Jun 19 '13 14:06

SgtPooki


People also ask

How do you use regex in VSCode search?

Vscode has a nice feature when using the search tool, it can search using regular expressions. You can click cmd+f (on a Mac, or ctrl+f on windows) to open the search tool, and then click cmd+option+r to enable regex search. Using this, you can find duplicate consecutive words easily in any document.

How do capture groups work regex?

Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d" "o" and "g" .

How do I change the regex code in Visual Studio?

How to enable VSCode regex replace. First, you need to press Ctrl + H on Windows and Linux, or ⌥⌘F on Mac to open up search and replace tool. In order to activate regex search and replace in VSCode, you have to click on the . * button near the input.

What regex does VSCode use?

Visual Studio uses . NET regular expressions to find and replace text.


2 Answers

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

  • Surround with (), display capture with $1, $2, $n

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

like image 119
SgtPooki Avatar answered Oct 02 '22 02:10

SgtPooki


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

like image 42
syonip Avatar answered Oct 02 '22 01:10

syonip