In Part 1 we discussed the "rules" of regular expression. In this article I will show you how to use the regular expression object inherent in VBScript 5. (If you do not have the VBScript 5 Scripting engine installed, refer to Part 1 for installation instructions.)
First things first: you need to create an instance of the
regexp object. This can be
accomplished with the following code:
There are a couple of nifty properties in the regexp object. One such property is the
property. We set this property equal to our regular expression. So, let's say that we are wanting to
search a string for a valid phone number (a very common regular expression-tutorial question). Let's
say that all phone numbers will have this form:
Note that there are no spaces in that string. So, our regular expression could look like:
Note: We need the backslashes before the parenthesis because the parenthesis are special characters (remember, they are used for grouping!)...
That says that we want to match strings that have a left parenthesis, three characters between zero and nine, a right parenthesis, three characters between zero and nine, a dash, and then four characters between zero and nine. Only strings that match this strict guideline will be found with our regular expression search.
IgnoreCase, which is false by default, determines if we want our search to
be case sensitive. The final property of the
regexp object is
determines if a regular expression should search the entire string for multiple matches, or if it should
just be satisfied with the first match it finds. Multiple matches are searched for when
Global is true,
and only match is searched for if
Global is false.
So, let's set these properties:
regexp object has three methods, but I am only going to focus on one of them right now.
Execute method searches for the pattern specified by the
in the string it is passed. It returns a collection of Matches. So, let's define the string that we
want to use our regular expression to search on:
The above code creates the string we are going to search (
strSearchOn), and executes the
Execute method returns a collection of Matches, which we assign to our
colMatches. You may be wondering what a Match is. Well, it is another object
that represents all of the strings we found. In our example, we would have found two matches,
"(123)654-3211" and "(873)392-1222".
Now, let's say that we want to display all of the matching strings... easy enough, we just need to step through the Matches collection and display the each match!
The above code will print out the number of matches we found, as well as each match.
Well, that's it! I hope you've learned a lot and are now excited about using regular expressions in your code! I will definitely follow this article up with other, related articles, so stay tuned! In closing, let me highly recommend that you check out Microsoft Beefs up VBScript with Regular Expressions, an article available on Microsoft's site.