Static refactoring with Visual Studio regular expressions

Regular expressions are a multi-tool in every developer toolbox. One of the places they can be useful is Quick Find and Quick Replace dialogs in Visual Studio. In this post, I’m going to show you how you can use the power of regular expressions in smart refactoring.

Changing an enum to string

Let’s assume I’d like to change an enum to a string in my application, cause I realized that this property can include a value that the user added by hand and cannot be predefined. Let’s have a look at this enum:

public enum EventType
{
    Unknown = 0,
    Concert = 1,
    Movie = 2
}

Now let’s try to find all the usages of this enum. For that task, I’m using a Quick Find in Visual Studio, Ctrl + F.

Have you noticed a blue rectangle in a Quick Find dialog? It is an option to search with a regular expression. Let’s enable that and switch to the Quick Replace dialog. You can do it with the toggle on the left side or with the Ctrl + H.

I entered EventType\.(\w+) expression that means, that it will start with a EventType string, then a regular dot, which I must escape with \. Next are parenthesis, which means that I’m starting a subexpression group, and /w+ will match a word character one or more times. I’m going to replace it with "$1", which is a standard quotation mark and $1 is a reference to the first group.

And the result is really good:

We can refine this expression a bit and add a name for a group.

By changing (\w+) to  (?<entryType>\w+) we have given a name to the results of this group. We can use it in the Replace With input.

Summary 

Creating a regular expression is a try-and-error process, where you would need to refine your expression a couple of times until it matches what you need. However, it can be really useful and with a manual job like that, can save a lot of time.

I hope that you learned something new today and if so, happy days! 💗 

One thought on “Static refactoring with Visual Studio regular expressions

  1. Pingback: Refactoring with reflection – Michał Białecki Blog

Leave a Reply

Your email address will not be published. Required fields are marked *