∟"Set oRegExp = New RegExp" - Creating RegExp Objects
This section describes steps on how to create a new RegExp object with a Set statement 'Set oRegExp = New RegExp'. oRegExp.Global and oRegExp.IgnoreCase used to set pattern match options.
We have discussed enough about the returning object structure of a pattern match operation.
Now let's look at how can we set up a pattern match operation:
1. Create an empty RegExp object with a "Set" statement and set it to a variable:
Dim oRegExp
Set oRegExp = New RegExp
Where "RegExp" is the name of the "RegExp" class;
"New" is an operator to create a new object out of a class;
"oRegExp" is Variant variable holding the new "RegExp" object.
2. Assign a regular expression string as the match pattern following regular expression rules.
Here are some examples of regular expressions - see a regular expression manual for more examples:
' A pattern to match any word ending with "ee".
' No sub matches defined.
oRegExp.Pattern = "\w+ee\s"
' A pattern to match any email address.
' 3 sub matches defined in the pattern.
oRegExp.Pattern = "(\w+)@(\w+)\.(\w+)"
3. Set match flags, "Global" and "IgnoreCase". For examples:
' Repeat matches on the entire string
oRegExp.Global = True
' Ignore cases while matching the pattern
oRegExp.IgnoreCase = True
Now the "RegExp" object, oRegExp, is ready to be used to match again any given string following operations:
' Returns True if the pattern matched at least once.
bFound = oRegExp.Test(string)
' Returns a copy of the given string with each match replaced.
sCopy = oRegExp.Replace(string, replacement)
' Returns a MatchCollection object containing matches.
Set oMatches = oRegExp.Execute(string)