I have a large ASP.NET project where I want to do a mass search and replace (about 3500 instances)
I want to change
If strErrorMessage.Length > 0
If strSomeString.Length > 0
If strWhatever.Length > 0
and any other similar call to the Length method from a string to the following
If Len(strErrorMessage) > 0
If Len(strSomeString) > 0
If Len(strWhatever) > 0
Anyway to reliably do this in one shot?
I can do a search and replace for something like
If *.Length > 0 --> If Len(*) > 0
This just won’t work though as it won’t understand how to rearrange it properly. Currently have VS2010 and N++ at my disposal.
Any ideas?
Using the Visual Studio Find/Replace (with the regex options enabled) you can use this:
Find what:
If {:a+}\.Length \> 0Replace with:
If Len(\1) \> 0Pattern explanation:
:a+= the:amatches an alphanumeric char, and the+matches at least one occurrence{}in{:a+}= Visual Studio regex’s way of “tagging” (i.e., capturing) an expression\>= the>must be escaped with a backslash since it’s a metacharacter in this regex flavor.\1= refers to the text matched in the tagged expression. The number1refers to the first (and only, in this case) tagged expression.You can read more about the MSDN regex reference for Find/Replace here.
As I had mentioned in my comment, I think using
Len()is a step backwards and ties your code down to theMicrosoft.VisualBasicnamespace. @drventure brought up a good point though, since calling.Lengthon a null value would throw an exception. Instead of checking the length you could use String.IsNullOrEmpty. In .NET 4.0 you can also use String.IsNullOrWhiteSpace.Instead of
If strErrorMessage.Length > 0you can use:If you’re interested in using this you can keep the original “Find what” pattern and change the “Replace with” pattern to this:
If Not String.IsNullOrEmpty(\1)