Visual Studio Find & Replace Regex

Once I learned about Regular Expressions, I was never really able to do any form of document searching or repetitive text adjustments without them. What I often come to appreciate in development environments is when their find and replace features accommodate regular expressions. Visual Studio is no exception, though Microsoft has their own special grammar which can be frustrating to decipher at first.

This afternoon I found myself needing to convert form elements in an HTML page to ASP.NET controls (<input type=”text”… to <asp:TextBox, etc.). Each of the form elements had corresponding names, but not IDs required for ASP controls. So, I rustled up a nice little Find & Replace regex to clone the name properties of each form element as an ID. Here is what I came up with:

Find: name=”{.#}
Replace:  id=”\1” name=”\1

The curly brackets are MS’s way of tagging a portion of your Find for reuse later in the Replace (the “\1“). The period (.) does exactly what you think it does. The pound sign (#), however, is MS’s way of doing a lazy match rather than a greedy one. Typically to do this you would type “.+?” to keep the “+” from grabbing as much of the string that matches as possible:

Greedy: 
<asp:TextBox runat="server" name="applicant_preferred_name" maxlength="100" />
Lazy:
<asp:TextBox runat="server" name="applicant_preferred_name" maxlength="100" />

Because this took a little looking to remember, I figured I’d make a post about it (if not just for my personal reference in the future :P)

MSDN Regex Article: http://msdn.microsoft.com/en-us/library/2k3te2cs(v=vs.80).aspx

Tagged with: , ,
Posted in Blurbs