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.
In Visual Studio’s “Find” field:
In “Replace” field:
I split the find pattern into three groupings by parentheses. Since parentheses carry regex significance, I encoded
), 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
Is there a more efficient way to do this? Most likely. But, this method worked.
Leave a Reply