Find and Replace using regular expressions

Taking Visual Studio’s Find and Replace up one notch, with tagged expressions.

From the archive. First published on the Programming Recipes blog on 29 March 2012. Kept as it was written, so details may have moved on since.

OriginalArchived copy

Decided today to take my Find and Replace up one notch:

I got this code:

var parameters = new
{
labSoilAnalysis.ID,
labSoilAnalysis.Year,
labSoilAnalysis.Season,
labSoilAnalysis.RegionID,
labSoilAnalysis.FieldID
};

that I want to change to:

var parameters = new
{
ID = labSoilAnalysis.ID,
Year = labSoilAnalysis.Year,
Season = labSoilAnalysis.Season,
RegionID = labSoilAnalysis.RegionID,
FieldID = labSoilAnalysis.FieldID
};

Using regular expressions I ended up using:

Visual Studio’s Quick Replace panel with “{labSoilAnalysis}{.}{.+[^,]}” in Find what, “\3 = \1\2\3” in Replace with, Look in set to Selection, and Use: Regular expressions ticked

The expression in the find box: {labSoilAnalysis}{.}{.+[^,]} is 3 tag expressions that is each assigned a number that I use in the Replace box, to reorder the code.

I know that it can be done in a beter way but me being a newbie to regex… maybe some of the big guns can help to make it beter, please post a comment with your take!