Macro to Find Regular Expressions in Code

Introduction

Recently I needed to find all the embedded strings inside some Legacy MFC C++ code and help refactor it.  In searching for the strings, I ended up with some legitimate embedded strings such as TRACE statements.  I wanted to eliminate all the lines containing Trace statements without eliminating the embedded strings I care about fixing.  I turned to the Macro capability of the VS.NET IDE

Summary

The macro below will allow me to search for a particular regular expression of text in my code file and delete the line containing that expression:

Sub TemporaryMacro()

' Set loop for a rediculously large number of iterations

For j = 1 To 10000

' go to the top of the file

DTE.ActiveDocument.Selection.StartOfDocument()

' send up the find structure with what you want to search upon

DTE.Find.MatchCase = True

DTE.Find.FindWhat = "TRACE.\("

DTE.Find.Target = vsFindTarget.vsFindTargetCurrentDocument

' also set all the find options including regular expressions

DTE.Find.MatchCase = True

DTE.Find.MatchWholeWord = False

DTE.Find.Backwards = False

DTE.Find.MatchInHiddenText = True

DTE.Find.PatternSyntax = vsFindPatternSyntax.vsFindPatternSyntaxRegExpr

DTE.Find.Action = vsFindAction.vsFindActionFind

' break out when we can't find any more occurences

If (DTE.Find.Execute() = vsFindResult.vsFindResultNotFound) Then

Throw New System.Exception("vsFindResultNotFound")

End If

' select the line containing the offending search string and delete it

DTE.ActiveDocument.Selection.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstColumn)

DTE.ActiveDocument.Selection.LineDown(True)

DTE.ActiveDocument.Selection.Delete()

Next j

End Sub