Sunday, July 8, 2007

Using Regular Expressions in Find & Replace within Visual Studio

This is not much of an adventure but more of a quick tip. As you may know from my other adventures I have realized that one of the key features in .Net to utilize is regular expressions. So, to help me develop in this area I am trying to use them appropriately wherever possible. One place that you may not be aware of is in the "Find & Replace" screen in Visual Studio.

Here is the tip. Suppose you have a whole line you want to delete from many locations. For example:
'Deletes a record

You could do a find and replace on 'Deletes a record but then you'd be left with an extra blank line in all of those locations. Extra blank lines can drive you crazy when you are trying to maximize screen real estate. So, instead of a simple replace of 'Deletes a record do this:
Replace this: \n+\s*\'deletes a record\n

Then make sure to select "Regular Expressions" in the "Use:" selection of the "Find & Replace" screen.

Here's a quick explanation of the syntax of \n+\s*\'deletes a record\n
\n stands for "New Line"\
+ stands for "1 or more matches" (of new line in this case)
\s stands for a space (or tab or other whitespace characters)
* stands for "zero or more matches" (of blank spaces in this case)
I had to "escape" the apostrophe with a \ because ' has special meaning in the regular expressions engine in VS so by typing \' I am telling the search engine that I really want an apostrophe.
Then of course my text to search for (deletes a record)
\n for the trailing new line character that I want deleted.

A simpler choice could have been
\'deletes a record\n
But without placing the requirement of at least 1 new line before and optionally some spaces there is a chance that I would match something like this:
Some Code 'deletes a record
return true

And turn it into this:
Some Code return true

Which would not compile.

So, using regular expressions in the "Find & Replace" window can be tricky but without daily (or at least weekly) practice on regular expressions I probably won't see real improvement. Because I do not always have a need for writing regular expressions using them within the "Find & Replace" window will allow me to stay sharp.

Thanks for sharing this adventure with me.

1 comment:

Rajeev said...

Nice Information: I build a tool to ease the Regular Expressions Path: Download (always free) and Take a look :