Thursday, 10 March 2016

Advanced text replacements in Visual Studio using RegEx

This is just a quick tip about making advanced text replaments in Visual Studio.

You are probably used to the "Replace in Files" tool accessible through the Ctrl+Shift+H shortcut (see below). As you already know, you can make text replacements in multiple files, entire solutions, etc.


Using Regular Expressions (you can test them first using this site), you can make quite complex replacements that are really handy when refactoring code. Especially when those changes appear in many different places.

For instance, let's say you were accessing attributes of a class all around your code. Something like:

                        nd.Attributes["ATTRIB_NAME"].Value = "ATTRIB_VALUE";                        

And that you want to change that, replacing with a call to a method. Something like:

nd.SetAttributeValue("ATTRIB_NAME", "ATTRIB_VALUE");

First, you need a way to find all appearances of something similar, no matter what's inside those strings (ATTRIB_NAME, ATTRIB_VALUE). That can be easily achieved with the following "Find What" argument:

.Attributes\["(.*)"\].InnerText = (.*);

It includes the (.*) RegEx, which basically matches any string. By using the brackets (), it will also instruct Visual Studio to tag whatever it matches the RegEx in each find-and-replace operation. That way, we can use that values in the "Replace With" argument:

.SetAttributeValue("$1", $2);

By using $1..$n, we specify found strings tagged in the "Find What" parameter. That way, the resulting replacement will include what we want, and re-use whatever was found in the original string. 

This page includes more information about using RegEx in Visual Studio.

No comments: