Geeks With Blogs
Liam McLennan hackingon.net

Visual studio supports relatively advanced string manipulation via the ‘Quick Replace’ dialog.

Today I had a requirement to modify some html, replacing line breaks with unordered list items. For example, I need to convert:

Infrastructure<br/>
Energy<br/>
Industrial development<br/>
Urban growth<br/>
Water<br/>
Food security<br/>

to:

<li>Infrastructure</li>
<li>Energy</li>
<li>Industrial development</li>
<li>Urban growth</li>
<li>Water</li>
<li>Food security</li>

This cannot be done with a simple search-and-replace but it can be done using the Quick Replace regular expression support. To use regular expressions expand ‘Find Options’, check ‘Use:’ and select ‘Regular Expressions’

image

Typically, Visual Studio regular expressions use a different syntax to every other regular expression engine. We need to use a capturing group to grab the text of each line so that it can be included in the replacement. The syntax for a capturing group is to replace the part of the expression to be captured with { and }. So my regular expression:

{.*}\<br/\>

means capture all the characters before <br/>. Note that < and > have to be escaped with \.

In the replacement expression we can use \1 to insert the previously captured text. If the search expression had a second capturing group then its text would be available in \2 and so on.

Visual Studio’s quick replace feature can be scoped to a selection, the current document, all open documents or every document in the current solution.

Posted on Wednesday, June 16, 2010 2:55 PM | Back to top

Copyright © Liam McLennan | Powered by: GeeksWithBlogs.net