Category Archives: .NET

Regex in Visual Studio

If you’re a daily user of Visual Studio like i am, then you’ll appreciate this nice feature I recently actually figured out how to use: backreferences in regular expressions built within search and/or search & replace operations.

Let’s say I have the following code from a VB to C# conversion, that incorrectly uses method parentheses ( ) when it should be using index brackets [ ] .


if ((grid.Items(intCounter) is GridDataItem) &&grid.Items(intCounter).Display)
{
CheckBox chkSelectForAction = (CheckBox)grid.Items(intCounter).FindControl("chkVal");
if (chkSelectForAction.Checked & chkSelectForAction.Visible)
{
ReturnedList.Add(grid.DataKeyValues(grid.Items(intCounter).ItemIndex)("BindID"));
}
}

And now  let’s say this construct of “.Items(val)” is all over the place, and i want to change it to the correct “.Items[val]” construct.  The obvious problem is that for each match of “.Items(val)”  the inner value (val) may be completely different.

Here is where the power of regular expressions and backreferences helps us.

In the Visual Studio “Find & Replace” window, type the following into the “Find What:” box:

Items\({[^\)]+}\)

In the “Replace With: box, type:

Items\[\1\]

Now let’s explain.  In the first “find” regex, we tell it to find the literal “Items” then the character “(”  — using an escape character \( since we don’t mean to open a match expression.  Then we open the backreference block { }.  This tells VS that when a match is found, to store it in the first backreference (which is accessed via \1).  Then we tell it to find 1 or more of any character other than a closing parenthesis “)” — via [^\)] . This is so the regex doesn’t overrun the bounds of our indexer.  Then we close it up with closing the backreference block } and the ending parenthesis literal \).

Now, when each match of “Items(xxx)” is found, it will store xxx into the backreference of \1 (since there will be only one occurance of the “xxx” part in each match.

And in the same execution, it will fire the “Replace with” block, which accesses this backreference, replacing the entire match with Items[xxx].

And that’s it!  You can probably see how powerful this be when you consider global search and replace operations.  The only trick is to try out your new regex on a selection or single page prior to executing it within an entire project or solution (since you can’t “undo” that operation).

Happy regexing!

4 Comments

Filed under .NET, ASP.NET, C#, Regular Expressions