What About VBScript?

Andrew Clinick

When VBScript 5.0 beta 2 (due later this month) introduces support for regular expressions modeled very closely on the JScript® and Perl implementations, most of the information contained in this article will be applicable to VBScript.
      Regular expressions are implemented in an external object, Scripting.RegExp, which you can access in VBScript using the CreateObject command.


 set myRegExp = CreateObject("Scripting.RegExp")
The object model for Scripting.RegExp is very similar to that of the corresponding JScript objects. You have a pattern property which you set to be your regular expression. Once you've done that you can use it by calling either the test, execute, or replace methods on the objects. The execute method will return a collection of matches found in the string you pass into the exec method. It will also set the $1through $9 properties on the object with the last set of results just like JScript.
      For example, this is how you would test for a string:

 Function RegExpTest(patrn, strng)
 Dim regExp, Match, Matches 'Create variable.
 Set regExp = CreateObject("Scripting.RegExp")
 regExp.Pattern = patrn 'Set pattern.
 regExp.IgnoreCase = True 'Set case-insensitivity.
 regExp.Global = True 'Set global applicability.
 Set Matches = regExp.Execute(strng) 'Execute search.
 For Each Match in Matches 'Iterate Matches collection.
     RetStr = RetStr & "Match " & I & " found at position " 
     RetStr = RetStr & Match.FirstIndex & ". Match Value is "
     RetStr = RetStr & Match.Value & "'." & vbCRLF
 Next
 RegExpTest = RetStr
 End Function
 MsgBox(RegExpTest("is.", "IS1 is2 IS3 is4"))
The keen-eyed will have noticed that this regular expression object is implemented as a COM object, so you can use it anywhere you can use a COM object: VBScript, Visual Basic, Visual Basic for Applications, or even JScript. More information and full documentation for this object will be available on the Microsoft Scripting Web site (at http://msdn.microsoft.com/scripting/) as soon as the next beta of Microsoft Internet Explorer 5.0 is released.