DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Collin M. Barrett
Collin M. Barrett

Posted on • Originally published at collinmbarrett.com on

Wildcard Regex Find and Replace in Visual Studio

Glasses and Computer

Wearing Out the Delete Key

When fixing a bug recently, there was a pattern in scope of where I was working that looked something like this:

MyObjectCollection.Add(new MyObject(0, "0100", "Name"))MyObjectCollection.Add(new MyObject(0, "0200", "Address"))

The method’s developer used this pattern about one hundred times in the same method! To iteratively refactor, I created an extension overload method for Add() which hid and de-duplicated the repetitive MyObject instantiations.

Refactoring the original method, however, then required much manual selecting and deleting. I would have to delete each instance of new MyObject( and ). I could use standard find and replace for all instances of new MyObject(, but how would I remove their corresponding closing parenthesis?

Regex Find and Replace

Rather than spending the time to delete the refactored code manually, I decided to spend (albeit as much) time automating it with regex find and replace.

Regex is powerful, but I use it so rarely that it is not a skill in which I have developed any meaningful chops. When I finally determined a usable pattern for the issue described above, I had to jot it down to reference later.

TL;DR Solution

In Visual Studio’s β€œFind” field:

(MyObjectCollection.Add(new MyObject)(([^)]*))())

In β€œReplace” field:

MyObjectCollection.Add$2

Solution Explanation

I split the find pattern into three groupings by parentheses. Since parentheses carry regex significance, I encoded ( and ), the existing parenthesis characters. Visual Studio replaces the $2 variable in the Replace field with the contents of the second parenthetical grouping in the Find field. So, this solution replaces each entire line captured by the find regex pattern with the replace regex pattern (preserving the unique MyObject constructor parameters with the $2 variable).

Diagram of Regex Find and Replace Solution
Diagram of Regex Find and Replace Solution

Is there a more efficient way to do this? Most likely. But, this method worked.

via StackOverflow

Top comments (0)

🌚 Browsing with dark mode makes you a better developer by a factor of exactly 40.

It's a scientific fact.