Posted November 13, 2008 and filed under Technology    tags:  ,

There is a function I use with almost all of my VBScripts that I am asked to write that I thought would be helpful to share.  The scenario is that you want to check if a variable contains a matching string.  Usually you would use an Instr(var, pattern) method to identify a match.  While effective you have a couple of points to consider.  Using the instr method you have to worry about case sensitivity (ex. Happy vs happy).   You also can’t handle variations like Server01 and Server 02 without running the instr method twice.  Other issues exist but lets move to my suggestion.

I find the following function ends up in almost every one of my scripts:

Function RegExpTest(strInput, strPattern)
    Dim objRegExp : Set objRegExp = New RegExp
    objRegExp.IgnoreCase = True
    objRegExp.Global = False
    objRegExp.Pattern = strPattern
    RegExpTest = objRegExp.Test(strInput)
    objRegExp.Pattern = ""
end function

Now when I need to test for a matching string value I simply use the following syntax:

if RegExpTest("MyServer01", "server") then
    wscript.echo "Found a match"
end if

Since I am using Regular Expressions to test the match I can use expressions in my patterns to find either MyServer01 or MyServer02:

if RegExpTest("MyServer01", "MyServer0(1|2)") then
    wscript.echo "Found a match"
end if

Let me know if this helps you or if you find this useful!

If you liked this article why not share it with others?

Kick it up to DotNetKicks.com

Add comment


(Will show your Gravatar icon)

biuquote
Loading