Multiline Replacement With Visual Studio

Multiline Replacement With Visual Studio

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.

image

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 HeaderMatch “#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.
\#endregionMatch 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!

This article is part of the GWB Archives. Original Author: Alois Kraus

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.