February 5, 2010

Visual Studio Tip #2: Fear the Regex Magic No More

Here's a quick tip from the trenches.

I'm sure lots of developers had to - one day or another - weigh between replacing some text by hand or finding a regular expression to automate the process. Given that I'm not a regex master, it's often less time consuming for me to do it by hand for let's say a dozen of lines. Like our previous tip this is no new bleeding edge feature in VS but it's certainly often ignored.

Let's say you have a bunch of constants that you want to move into a config file where the variable name is the key and the value is... well the value. VS helps you compose your regex thanks to these little helpers:

Back to our constant:
private const string ftpLocation = "ftp://localhost/repository";

will be replaced as
<add key="ftpLocation" value="ftp://localhost/repository">

with this regex:
^([a-z ]*) {[a-zA-Z_]+} = "{[A-Za-z.\/\:\-]+}";

which is basically composed as follows:


select a new line

([a-z ]*)

select multiple characters composed of lowercase letters or space

private const string


select the next group of characters composed of letters or underscore
this group is replaceable: {}


= "

followed by space - equals - quote

= "

= "

followed by space - equals - quote

= "


select the next group of characters composed of letters or . or / (escaped) or : (escaped) or - (escaped)
this group is replaceable: {}



followed by quote - semicolon


Don't forget to check the regular expression option on the find dialog.
You replace your selection by the desired format where you order your tag replacements:
<add key="\1" value="\2" />

Here's the final result on a replace all.

Of course this can be done in any Text Editor supporting regular expressions but be aware that the Visual Studio dialect differs a little from the usual standard.

kick it on DotNetKicks.com
Shout it

1 comment:

  1. another version has been release this year blogengine 1.6. It has new additional features

    now it can prevent comment spam filter that has ability to plugin custom filtering

    modules.It has improve outgoing emails and more improvement and fixes for this 1.6