January 8, 2018

Wildcard Regex Find and Replace in Visual Studio

Disclaimer: I imported this post from WordPress to Jekyll on 9/2/23. Forgive the misformatting until I get a chance to clean it up.

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:


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](/assets/img/regexSolutionExplanation_collinmbarrett.jpg)](/assets/img/regexSolutionExplanation_collinmbarrett.jpg)
Diagram of Regex Find and Replace Solution

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

via StackOverflow