Ad-hoc String Manipulation With Visual Studio
Posted
by Liam McLennan
on Geeks with Blogs
See other posts from Geeks with Blogs
or by Liam McLennan
Published on Thu, 17 Jun 2010 01:55:13 GMT
Indexed on
2010/06/17
3:13 UTC
Read the original article
Hit count: 309
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’
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.
© Geeks with Blogs or respective owner