2017年3月1日星期三

Use Regular Expression in Visual Studio 2015

It's a good method to use back reference in regular expression when you need to replace many items in a large file.

Suppose you want to delete </li> in a line like:

<li id="a1" class="a2">some text</li>

There are many lines like this, the id, class and text are all different, and you want to keep them. Then you can use back reference to do it.

choose  Edit -> Find and Replace -> Quick Replace

in the text box for search term, input:
<li id="(?<s1>w+)" class="(?<s2>w+)">(?<s3>.*$[a-zA-Z])</li>

in the text box for replacement term, input:
<li id="${s1}" class="${s2}">${s3}

make sure to set the Use Regular Expressions on, then click replace all. All done!

${s1}, ${s2}, ${s3} are called back reference, which will be kept untouched during the replacement.