Regular Expressions in VBScript
(Page 1 of 4 )
At this point in your scripting you’ve certainly come across VBScript’s InStr and Replace functions for searching and replacing within strings. While these string functions can come in pretty handy, they are also intrinsically limited. It’s time to step up into the Big Leagues and learn how to search and replace based on patterns.
Like most other programming languages, VBScript uses regular expressions to perform pattern matching. A regular expression is a textual expression that contains symbols and literal characters used to match a pattern of characters. These can be extremely simple or scaled to be very complex, but if you take things one step at a time you’ll pick them up very easily.
So when would you use regular expressions? Well, for starters you can have much more powerful string replacements. You might also use regular expressions to validate form entry in an HTML application or ASP page. You’ll understand this better and realize the flexibility as you see some real-world examples.
VBScript provides the RegExp object for creating and handling regular expressions. It provides a series of methods and properties for searching and replacing based upon regular expression patterns.
Set objRegExp = New RegExp
The RegExp object is a native VBScript object. However, it is not instantiated by default like most VBScript objects you’ve seen so far. Thus it must be instantiated manually by referencing the RegExp class using a New statement. A new statement simply returns the object instantiated by a specified class.
objRegExp.Global = False
objRegExp.IgnoreCase = True
objRegExp.Multiline = False
objRegExp.Pattern = "some pattern"
The RegExp class provides several properties for controlling its behavior when matching or replacing. The Global property is used to determine whether a RegExp replacement will replace all occurrences or only the first match found. The IgnoreCase property accepts a Boolean value that indicates whether a match should be case sensitive. The Multiline property is an undocumented property that indicates whether whitespaces should match line break characters. By default, all three of these properties are set to False. Finally, the Pattern property is a text string pattern that determines what matches are found. You’ll learn more about constructing patterns in a bit.
Next: Searching and Replacing >>
More Windows Scripting Articles
More By Nilpo