Multiline Replacement With Visual Studio
Posted
by Alois Kraus
on Geeks with Blogs
See other posts from Geeks with Blogs
or by Alois Kraus
Published on Sun, 30 May 2010 05:53:35 GMT
Indexed on
2010/05/30
7:12 UTC
Read the original article
Hit count: 352
I had to remove some file headers in a bigger project which were all of the form
#region File Header
/*[ Compilation unit ----------------------------------------------------------
Name : Class1.cs
Language : C#
Creation Date :
Description :
-----------------------------------------------------------------------------*/
/*] END */
#endregion
I know that would be a cool thing to write a simple C# program use a recursive file search, read all lines skip the first n lines and write the files back to disc. But I wanted to test things first before I ruin my source files with one little typo. There comes the Visual Studio Search and Replace in Files dialog into the game. I can test my regular expression to do a multiline match with the Find button before actually breaking anything. And if something goes wrong I have the Undo button.
There is a nice blog post from Paulo Morgado online who deals with Multiline Regular expressions. The Visual Studio Regular expressions are non standard so you have to adapt your usual Regex know how to the other patterns. The pattern I cam finally up with is
\#region File Header:b*(.*\n)@\#endregion
The Regular expression can be read as
\#region File Header | Match “#region File Header” \# Escapes the # character since it is a quantifier. |
:b* | After this none or more spaces or tabs can follow (:b stands for space or tab) |
(.*\n)@ | Match anything across lines in a non greedy way (the @ character makes it non greedy) to prevent matching too much until the #endregion somewhere in our source file. |
\#endregion | Match everything until “#endregion” is found |
I had always knew that Visual Studio can do it but I never bothered to learn the non standard Regex syntax. This is powerful and it is inside Visual Studio since 2005!
© Geeks with Blogs or respective owner