Using Regular Expressions With Find And Replace In .Net IDE

06-06-2012

Use any regular expression to make your match.

Then use {} pairs to define blocks of the search string you want to use in the Replaced string.

Example: following find and replace strings will replace all occurrences ” report(number) ” to  ” // report – number ” in the following sample code.

Sample Code – Before running find and replace with regular expressions

” report(number) ” —->  ” // report – number ”

(Note the code below has no specific connection with this topic. It’s just used as a sample text)

         if (StartDate != null && EndDate != null)
            {
                report(2);
                DateTime correctedEndDate = new
DateTime(((DateTime)EndDate).Year, ((DateTime)EndDate).Month, 01);
                report(3);
                correctedEndDate = correctedEndDate.AddMonths(1);
                report(4);
                correctedEndDate = correctedEndDate.Subtract(new TimeSpan(1,
0, 0, 0));
                report(5);
                AdditionalWhere = string.Concat(AdditionalWhere, ... ... ...
                report(6);
                DateFilter = AdditionalWhere;
                report(7);
            }

Find Expression: {report}({[0-9]*});
(Note the pair of braces defining the pieces I want to use again in the replacing text)

Replace Expression: // 1 – 2

Sample Code – After running find and replace with regular expressions

            if (StartDate != null && EndDate != null)
            {
                // report - 2
                DateTime correctedEndDate = new
DateTime(((DateTime)EndDate).Year, ((DateTime)EndDate).Month, 01);
                // report - 3
                correctedEndDate = correctedEndDate.AddMonths(1);
                // report - 4
                correctedEndDate = correctedEndDate.Subtract(new TimeSpan(1,
0, 0, 0));
                // report - 5
                AdditionalWhere = string.Concat(AdditionalWhere, ... ... ...
                // report - 6
                DateFilter = AdditionalWhere;
                // report - 7
            }

Menol
ILT

This entry was posted in Microsoft .Net Framework and tagged , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *