HOW TO Find and Replace Characters Using Regular Expressions in Visual Studio

There was a question on ASP.NET Forums to find a pattern using regular expressions to match the following strings in code within Visual Studio -
href="ProgramInformation.aspx?ID=TX"
href="ProgramInformation.aspx?ID=NY"
so that they can be replaced with the following strings -
href="javascript:SetStateCode('TX')"
href="javascript:SetStateCode('NY')"

Most editors support regular expressions to find and replace characters. Visual Studio supports it as well but has it's own regular expression dialect.

Tagged expressions aid replacements in a regular expression search by extracting a specific set of characters that are required to be manipulated. In a single find/replace, you can have up to 9 tagged expressions. To tag our search criteria, we place {} around the criteria.

For the above requirement, we have to capture just the value of ID from the URL set to the HREF property and use it to build another string. To accomplish this, in the Find and Replace dialog box (Ctrl + H or Edit > Find and Replace > Quick Replace), place this in the "Find what:" box -
ProgramInformation.aspx?ID={[A-Z]+}

and this in the "Replace with:" box
javascript:SetStateCode('\1')

Click Replace or Replace All to change a single or multiple instances of the matching pattern.

Find and Replace Characters Using Regular Expressions in Visual Studio

Comments

  1. I have been wondering how to do this. I tried once and never got it to work, so I gave up. Thanks!

    ReplyDelete

Post a Comment