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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: