Freigeben über


Regular Expression support in Visual Studio 2008

Since I write a lot of Silverlight and WPF applications, I make heavy use of Visual Studio, and when I work with large XML files it is very time saving to know how to use Visual Studio’s Regular Expressions search support. Every time I use it  though I invariably forget how to write RegEx searches, since I use it so seldom. So as the proverb goes: the weakest ink is better than the best memory. Perhaps you may get some use out of it.

Regular Expression search is not on by default. To turn it on you need to expand the options section in the Find and Replace dialog. RegEx search cannot be on by default since certain RegEx characters have completely different meaning that the literal characters and so would cause conflict if both were enabled.

SearchReplaceRegExCA1Z6T88

The Complete Character List is conveniently linked off the menu shown when clicking the arrows to the right of the find and replace Textboxes. I tend to learn much more quickly by example, and this page does provide *some* examples, so while useful, it doesn’t contain as many as I’d like. So here are two more for now:

\<xdate\>(.*)

Finds and selects the following node to the end of the line: <xdate>11/14/2008</xdate>

This is handy if you need to remove or modify an XML node. Note that the angle brackets are escaped with backslashes. The parentheses' group the period which allows any character and the asterisk which signifies zero or more characters before the carriage return.

\n~((.+)\n)

Finds and selects carriage returns that have empty lines following them. This is handy if you want to compact empty vertical space. Essentially the logic is: Find a carriage return, but only one that precedes a line with a blank carriage return. This search will not find a line if it has spaces contained in the empty line, so you would need to modify it.

 

I only provided two examples, but if you know of any good RegEx resources please provide a link in the comment, or you can tweet me on twitter.

Comments