Saturday, August 18, 2012

Visual Studio 2010 Find/Replace with Regular Expressions

I recently encountered a situation that required that I change a nontrivial amount of strings in multiple files where the strings were predictable except for and id. The solution was using regular expressions in Visual Studio. Regular expressions in Visual Studio give to you all the power of .Net's engine plus some useful additions. I am sure there is a way to reduce the escaping, but it worked for me. Here are some examples, some of them are changed slightly from the previous example to accommodate a slightly different case. I am not going to comment on each as the examples should speak for themselves.
Find Regular Expression:
[$]\(\'input\[id[$]=\\\'{:i}\\\'\]\'\)\.focus\(\);

Matches string:
onfocus="$('input[id$=\'btnName\']').focus();"

Replace:
focusCtrl(\'\1\');

Find Regular Expression:
[$]\(\"input\[id[$]=\'{:i}\'\]\"\)\.focus\(\);

Test match string:
$(function () { $("input[id$='btnName']").focus(); });

Replace:
focusCtrl(\'\1\');

Find Regular Expression:
return process\(\'{:i}\', \'{:i}\'\);

Test match string:
return process('txtNameID', 'txtName');

Replace:
return process(\'\1\', \'\2\', \'<%= NameID %>\');

Result:
return process('txtNameID', 'txtName', '<%= NameID %>');

Find Regular Expression:
alt=\"Validation Error\" title=\"[^"]+\" src="/_layouts/images/EXCLAIM.GIF"

Test match string:
<img alt="Validation Error" title="Name is required" src="/_layouts/images/EXCLAIM.GIF" />

Replace:
onprerender="Validator_PreRender" runat="server"

Find Regular Expression:
alt=\"Validation Error\" title=\"[^"]+\" src="/_layouts/images/EXCLAIM.GIF"

Test match string:
<img alt="Validation Error" title="Name is required" src="/_layouts/images/EXCLAIM.GIF" />

Replace:
onprerender="Validator_PreRender" runat="server"

Find Regular Expression:
\<img alt=\"Validation Error\" title=\"[^"]+\" src="/_layouts/images/EXCLAIM.GIF" /\>[ ]*

Test match string:
<img alt="Validation Error" title="Name is required" src="/_layouts/images/EXCLAIM.GIF" />

Replace:
<img onprerender="Validator_PreRender" runat="server" />

Find Regular Expression:
\<span class="ms-error"\>\<img src="/_layouts/images/EXCLAIM.GIF" /\>\</span\>[ ]*

Test match string:
<img alt="Validation Error" title="Name is required" src="/_layouts/images/EXCLAIM.GIF" />

Replace:
<img alt="Validation Error" title="" src="/_layouts/images/EXCLAIM.GIF" />

No comments: