Thursday, January 29, 2009

Search and Replace in Visual Studio 2005

I usually have to look this up, so I am posting it to my blog.

Visual Studio 2005 has a "Regular Expression" option on the "search and replace" dialog. (Previous .Net editions had it as well.) I occasionally want to rewrite several lines of text without writing a macro or wearing out my fingers. Here's what I do ...

If I have a file with several lines of

DECLARE R1 = VC WITH CONSTANT("TEST1")
DECLARE R20 = VC WITH CONSTANT("TEST2")
DECLARE R31 = VC WITH CONSTANT("TEST3")
DECLARE R42 = VC WITH CONSTANT("TEST4")

And I would like to convert these to

SET R1 = "TEST1"
SET R20 = "TEST2"
SET R31 = "TEST3"
SET R42 = "TEST4"

I would search for "declare [R|r]{.*} = .* with constant\({.*}\)" and replace with "set r\1 = \2" (don't add quotes into the search dialog).

This grabs the text in curly braces and assigns it to \1 and \2, so I can re-assemble it as I wish. I had to use a backslash in front of the parenthesis since otherwise this is seen as part of the reg-ex and not as a literal.

Labels: ,