Wednesday, January 11, 2012

How to write regexs matches that span multiple lines in Visual Studio search

Visual Studio has its own weird syntax for searching with regular expressions. Here's how to make a match across multiple lines. Given the sample XSL blocks below
<xsl:apply-templates select="Alph" mode="frobit"/>
<xsl:apply-templates select="Bob" mode="zap"/>
<xsl:apply-templates select="Cam"/>
I want to match the two statements with the mode="frobit", even though the first one has a carriage return in the middle. In VS, you'd use this regex statement to match just the first and last lines, skipping Bob with mode="zap":


The first bit, select.*\n, is standard Perlish for "match from the word select to the end of line character, \n."

The at sign @ is VS's way of asking "please can you find zero or more carriage returns, but only as few as needed." The alternative is the "greedy" match, using an asterisk *, which says "find as many lines as you can ending in carriage returns before you hit mode="frobit", so the match in this case would make one giant match, including all of the text from select="Alph" all the way to the last "frobit" on Cam, capturing poor Bob in the middle along the way.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.