Comparing Apples to Oranges

I’ve spent some time lately exploring searching and replacing techniques in a variety of scripting languages.  I hope to share some of these experiences later. Right now I wanted to briefly share a tip when searching for text using VBScript.  This is a common task and one that causes many novice scripters more than a little grief.

A typical VBScript expression is to use InStr() to determine whether a given substring exists within a larger string. In a related vein, you might use the Replace function to replace all instances of a given string with another. The problem is how you accomplish that comparison.  By default both functions perform a binary comparison. This means that “APPLE” and “APPLE” will match, but “APPLE” and “Apple” won’t. What you need to do is perform a text comparison which ignores case. 

Both InStr and Replace have an optional parameter to specify the comparison method. You can use the VBScript constants of vbTextCompare or vbBinaryCompare.  If you use the former, I strongly recommend you use the complete syntax for each function. In fact, you’ll likely get an error if you don’t.

I’ve put together a sample script that demonstrates how the different techniques work.

s=”The quick brown fox used Primalscript. The fox was smart!”

‘FOX (or any other case formatting such as fOX) only works with vbTextCompare
‘fox works in all cases since it is an exact match
strFind=”FOX”

WScript.Echo “Using simple defaults”
If InStr(s,strFind) Then
    WScript.Echo “Found with using defaults”
    s2=Replace(s,strFind,”dog”)
    WScript.Echo s2
Else
    WScript.Echo “Not found with defaults”
End If

WScript.Echo String(20,”*”)

WScript.Echo “Using vbBinaryCompare”
If InStr(1,s,strFind,vbBinarycompare) Then
    WScript.Echo “Found with vbBinaryCompare”
    s2=Replace(s,strFind,”dog”,1,-1,vbBinaryCompare)
    WScript.Echo s2
Else
    WScript.Echo “Not found with vbBinaryCompare”
End If

WScript.Echo String(20,”*”)

WScript.Echo “Using vbTextCompare”
If InStr(1,s,strFind,vbTextcompare) Then
    WScript.Echo “Found with vbTextCompare”
    s2=Replace(s,strFind,”dog”,1,-1,vbTextCompare)
    WScript.Echo s2
Else
    WScript.Echo “Not found with vbTextCompare”
End If

Save this code to your computer. Run it with Cscript at a command prompt. Play around with different variations for strFind and you’ll quickly appreciate the differences. I’m not advocating you never use vbBinaryCompare or the default settings for InStr and Replace. I merely want you to understand the differences.