I swear by regular expressions… they are a tool that developers can use in many ways. Essentially it allows you to specific a wildcard search but with more restrictions. In layman’s terms, it helps you find shit.
Today’s lesson is on using regex for find/replace functionality within Visual Studio. I’m not going to teach you regular expressions, but I will show you how to easily use them within Visual Studio.
Say you have an xml comment that is ambiguous and is all over your entire project (say 167 times).
It looks like this.
///
It’s ambiguous because you’ll have multiple overrides of AddRange that take in an array, the custom collection itself, or maybe a generic list.
You’ll want to change it to a specific AddRange, or the more generic one.
///
There are 167 instances of this… Ohh Jake! What will we ever DO?
Start off by hitting CTL-H (find/replace)
You’ll want to “find” things that fit the description and replace them with a piece of the text you search against (which happens to be the wild card).
Here are the expressions
Find:
{[a-zA-Z]+}Collection.AddRange"/>
Replace:
1Collection.AddRange(1[])"/>
Let’s break the expressions down…
Find:
The {} braces signify that I want to capture the values you find, to use them later in the replace. [a-zA-Z]+ tell it to find 1 or more characters before it hits Collection.AddRange
Replace:
The 1 tells Visual Studio to take whatever I captured in my first set of {} braces and use that in my replace value.
See… it’s really that simple, 2 minutes of writing regular expression code saved me the trouble of opening, finding, and replacing lines of text in 167 files.
Not bad.
