Monthly Archives: March 2006

Search and replace with Regular Expressions in Visual Studio .NET (2005)

Today I had to search and replace a text with a little variation in it in a very large project. This text looked like ‘if<zero or more spaces>(Null.IsNull(<object name>.<variable name>))’. I had to replace it with: ‘if (!<object name>.<variable name> > 0))’. This turns out to be quite a job, especially when you are not very experienced with Microsoft’s way of dealing with regular expressions. Finally I discovered a way to do the job. The expressions used for it are the following:

Search string: if[ ]*\(Null.IsNull\({:c+.:c+}\)\)
Replacement string: if (!(\1 > 0))

Note that the Regular Expression used to search does not entirely look likea normal RegEx. Microsoft seems to use their own kind of RegEx for search and replace. Important is that {} is not used to quantify like in RegEx (for instance: zo{1} matches ‘zo’ but not ‘zoo’), but to generate a tagged expression, which can be used in the replacement string by giving in \x whereby x represents a 1-base number (1st replacement = \1 and so on).

Hope I have been of some help for anybody out there :) . Please do not be concerned about posting a comment/question. I’ll do what I can to answer you soon!