Visual Studio Find and Replace with Regular Expresions

In this new post about some of my daily issues I’m going to finally get around to understanding Visual Studio find and replace with regular expressions. I have always used find and replace to update simple string matches, but now I want to up the ante and find and replace with regular expression matching. Regular expressions are awesome and I use them in my code, but never had the time or need to explore their use in Visual Studio find and replace. I hope it isn’t too different from normal regex.

First things first, let’s get grounded with a good references: MSDN – http://msdn.microsoft.com/en-us/library/2k3te2cs%28VS.100%29.aspx. Doesn’t look too difficult, just have to watch my typing very carefully.

Here’s what I want to do:

Find Application[“AnyValue”].ToString()

Replace with Config.Get<string>(“AnyValue”)

Here’s what I got:

Find Application\[{:q}\]\.ToString\(\)

Replace with Config.Get<string>(\1)

A little explanation:

\ – this is an escape character that lets us find characters that are used in regular expression notation (e.g. [ ] ( ) { } )

:q – match string that is enclosed in single or double quotes

{} – this tags values that we want to show up in the replace string. So, {:q} in find can be used as \1 in replace. Or, get the quoted value and put it where the \1 place holder is.

Click “Replace All,” run automated build and tests, and done son! Moved 200+ lines of code from using an archaic HttpApplicationState based global configuration to a custom abstract multi-tenant configuration. Research and implementation – 15 minutes, lesson learned – priceless.

Leave a Reply

    RSS Subscribe to comment feed.