VBScript
VBScript
Session 13 Session 13
?What we learn last session
?What we learn last session
What means error handling.What means error handling.
When to use On EWhen to use On Error statements.rror statements.
Using the error object.Using the error object.
Subjects for session 13
Subjects for session 13
Regulal ExpressionsRegulal Expressions
RegExp objectRegExp object
MethodsMethods
Properties.Properties.
Using the RegExp object.Using the RegExp object.
Matches collection object.Matches collection object.
Match object.Match object.
SubMatches collection object.SubMatches collection object.
PatternsPatterns
Position Matching.Position Matching.
Literals.Literals.
Character Classes.Character Classes.
Repetition.Repetition.
Alternation & Grouping.Alternation & Grouping.
Regular Expression
Regular Expression
?What is that
?What is that
So what are regular So what are regular expressions? Regularexpressions? Regular expressions provide tools for developing expressions provide tools for developing complex pattern matching and textual complex pattern matching and textual search-and-replace algorithms.
search-and-replace algorithms.
By creating patterns to match specificBy creating patterns to match specific
strings, a developer has total control over strings, a developer has total control over searching, extracting, or replacing data. searching, extracting, or replacing data.
In short, to master regular eIn short, to master regular expressions isxpressions is to master your data.
VBScript RegExp Object
VBScript RegExp Object
VBScript Version 5.0 provides regular expressionsVBScript Version 5.0 provides regular expressions
as an object to
as an object to developers.developers.
In design, the VBScriptIn design, the VBScript RegExpRegExp object is similarobject is similar
to JScript's
to JScript's RegExpRegExp andand StringString objects; in syntaxobjects; in syntax it is consistent with Visual Basic.
it is consistent with Visual Basic.
LetLet’’s describe the object and its properties ands describe the object and its properties and
methods. methods.
The VBScriptThe VBScript RegExpRegExp object provides 3object provides 3
properties and 3 methods to
properties and 3 methods to the user.the user.
Methods: Test, Replace, and ExecuteMethods: Test, Replace, and Execute
RegExp Object
RegExp Object
Pettern Property
Pettern Property
A string that is used to define A string that is used to define thethe
regular expression. regular expression.
This must be set before use of This must be set before use of thethe
regular expression object. regular expression object.
PatternsPatterns are described in moreare described in more
detail later. detail later.
RegExp Object
RegExp Object
IgnoreCase Property
IgnoreCase Property
A Boolean property that indicates if A Boolean property that indicates if
the regular expression should be the regular expression should be tested against all possible matches tested against all possible matches in a string.
in a string.
By default, IgnoreCase is set toBy default, IgnoreCase is set to
False. False.
RegExp Object
RegExp Object
Global Property
Global Property
GlobalGlobal - A Boolean property that- A Boolean property that
indicates if the regular expression indicates if the regular expression
should be tested against all possible should be tested against all possible matches in a string.
matches in a string.
RegExp Object
RegExp Object
Test Method
Test Method
TheThe TestTest method takes a string asmethod takes a string as
its argument and returns True if the its argument and returns True if the regular expression can successfully regular expression can successfully be matched against the string,
be matched against the string, otherwise False is returned.
RegExp Object
RegExp Object
Replace Method
Replace Method
TheThe ReplaceReplace method takes 2method takes 2
strings as its arguments. strings as its arguments.
If it is able to successfully matchIf it is able to successfully match
the regular expression in the the regular expression in the search-string
search-string, then , then it replaces thatit replaces that match with the replace-string, and match with the replace-string, and the new string is returned.
the new string is returned.
If no matches were found, then theIf no matches were found, then the
original search-string is returned. original search-string is returned.
RegExp Object
RegExp Object
Execute Method
Execute Method
TheThe ExecuteExecute method works likemethod works like
Replace
Replace, except that it returns a, except that it returns a
Matches
Matches collection object,collection object, containing a
containing a MatchMatch object for eachobject for each successful match.
successful match.
RegExp Object
RegExp Object
Using the RegExp object
Using the RegExp object
Here is a sample of a function where demostartes the usage of Here is a sample of a function where demostartes the usage of thethe
RegExp object. RegExp object. RegExp Function RegExp Function
FunctionFunction RegExpTest(pRegExpTest(patrn, atrn, strng)strng)
DimDim regEx, Match, Matches, strregEx, Match, Matches, str
SetSet regEx =regEx = NewNew RegExpRegExp
regEx.Pattern = patrnregEx.Pattern = patrn
regEx.IgnoreCregEx.IgnoreCase ase == TrueTrue
regEx.Global =regEx.Global = TrueTrue
SetSet Matches = regEx.Execute(strng)Matches = regEx.Execute(strng)
ForFor EachEach MatchMatch inin MatchesMatches
str = str & "Match found at positionstr = str & "Match found at position ““
str = str & Match.FirstIndex & ". Match Value is '"str = str & Match.FirstIndex & ". Match Value is '"
str = str & Match.Value & "'." & str = str & Match.Value & "'." & vbNewLinevbNewLine
NextNext
RegExpTest = strRegExpTest = str
EndEnd FunctionFunction
Line 1 Line 1 Function receives 2 Function receives 2 arguments arguments 1. pattern 1. pattern 2. String to search. 2. String to search. Line 3 Line 3 Creating a new Creating a new RegExp object, RegExp object, assign to assign to RegEx RegEx Line 4 Line 4 Set Pattern Set Pattern Line 5 Line 5 Set case Set case insensitivity insensitivity Line 6 Line 6 Set global Set global applicability applicability Line 7 Line 7 Execute Execute Search Search Line 8 Line 8 Iterate Iterate Matches Matches collection collection.. Line 9-11 Line 9-11
Retieving info from the Retieving info from the result.
RegExp Object
RegExp Object
Matches Collection Object
Matches Collection Object
TheThe MatchesMatches collection object is only returned ascollection object is only returned as
a result of the
a result of the ExecuteExecute method.method.
This collection object can contain zero or moreThis collection object can contain zero or more
Match
Match objects, and the properties of this objectobjects, and the properties of this object are read-only.
are read-only.
CountCount - A read-only value that contains the number- A read-only value that contains the number of
of MatchMatch objects in the collectionobjects in the collection..
ItemItem - A - A read-only value that enablesread-only value that enables MatchMatch objects to be randomly accessed from the
objects to be randomly accessed from the MatchesMatches
collection object. The
collection object. The MatchMatch objects may also beobjects may also be incrementally accessed from the
incrementally accessed from the MatchesMatches collectioncollection object, using a For-Next loop.
RegExp Object
RegExp Object
Match Object
Match Object
Contained within eachContained within each MatchesMatches collection object are zero orcollection object are zero or
more
more MatchMatch objects.objects.
These represent each successful match when using These represent each successful match when using regularregular
expressions. expressions.
The properties of these objects are also read-only, andThe properties of these objects are also read-only, and
contain information about each match. contain information about each match.
FirstIndexFirstIndex - A - A read-only value that contains the position withinread-only value that contains the position within
the original string where the match occurred. This
the original string where the match occurred. This index uses aindex uses a zero-based offset to record positions, meaning that the first zero-based offset to record positions, meaning that the first position in a string is 0.
position in a string is 0.
LengthLength - A read-only value that contains the total length of the- A read-only value that contains the total length of the
matched string. matched string.
ValueValue - A read-only value that contains the matched value or- A read-only value that contains the matched value or
text. It is also
RegExp Object
RegExp Object
Submatches Collection Object
Submatches Collection Object
Collection of regular expression submatch strings.Collection of regular expression submatch strings.
AA SubMatchesSubMatches collection contains individual submatchcollection contains individual submatch
strings, and can only be created using the
strings, and can only be created using the ExecuteExecute
method of the
method of the RegExpRegExp object.object.
TheThe SubMatchesSubMatches collection's properties are read-onlycollection's properties are read-only
When a regular expression is executed, zero or moreWhen a regular expression is executed, zero or more
submatches can result when subexpressions are submatches can result when subexpressions are enclosed in capturing parentheses.
enclosed in capturing parentheses.
Each item in theEach item in the SubMatchesSubMatches collection is the stringcollection is the string
found and captured by the regular expression. found and captured by the regular expression.
Patterns
Patterns
So What Does a Pattern Look Like?
So What Does a Pattern Look Like?
Regular expressions are almost another languageRegular expressions are almost another language
by itself. by itself.
VBScript derives its pattern set from Perl, VBScript derives its pattern set from Perl, and itsand its
core features are, therefore, similar to Perl. core features are, therefore, similar to Perl.
These sets of patterns can be broken down intoThese sets of patterns can be broken down into
several categories and areas several categories and areas
Position Matching.Position Matching.
Literals.Literals.
Character Classes.Character Classes.
Repetition.Repetition.
Alternation & Grouping.Alternation & Grouping.
Patterns
Patterns
Position Matching
Position Matching
Position matching involves the usePosition matching involves the use
of the ^ and $
of the ^ and $ to search forto search for
beginning or ending of strings. beginning or ending of strings.
Setting the pattern property toSetting the pattern property to
"^VBScript" will only successfully "^VBScript" will only successfully match "VBScript is cool." But it will match "VBScript is cool." But it will fail to match "I like VBScript."
Patterns
Patterns
Position Matching
Position Matching
^^ Only match the beginning of a string.Only match the beginning of a string.
"^A" matches first "A" in "An A+ for"^A" matches first "A" in "An A+ for
Anita. Anita.““..
$$
Only match the ending of a string.Only match the ending of a string.
"t$" matches the last "t" in "A cat in"t$" matches the last "t" in "A cat in
the hat the hat““..
Patterns
Patterns
Position Matching
Position Matching
\b\b Matches any word boundary.Matches any word boundary.
"ly\b" matches "ly" in "possibly"ly\b" matches "ly" in "possibly
tomorrow. tomorrow.““
\B\B
Patterns
Patterns
Literals.
Literals.
Literals can be taken to meanLiterals can be taken to mean
alphanumeric characters, ACSII, octal alphanumeric characters, ACSII, octal characters, hexadecimal characters, characters, hexadecimal characters, UNICODE, or special escaped
UNICODE, or special escaped characters.characters.
Since some characters have specialSince some characters have special meanings, we must escape them. meanings, we must escape them.
To match these special characters, weTo match these special characters, we precede them with a "\" in a regular precede them with a "\" in a regular expression
Patterns
Patterns
Literals
Literals
AlphanumericAlphanumeric Matches alphabetical and Matches alphabetical and numerical characters literally.numerical characters literally.
\n\n
Matches a new line.Matches a new line.
\f \f
Matches a form feed.Matches a form feed.
\r\r
Matches carriage return.Matches carriage return.
\t\t
Matches horizontal tab.Matches horizontal tab.
\v\v
Matches vertical tab.Matches vertical tab.
\?\? Matches ?Matches ? \*\* Matches *Matches *
Patterns
Patterns
Literals
Literals
\+\+ Matches +Matches + \.\. Matches .Matches . \|\| Matches | (pipe)Matches | (pipe)
\{\{ Matches {Matches { \}\} Matches }Matches } \\ \\ Matches \ Matches \ \]\] Matches ]Matches ] \[\[ Matches [Matches [
Patterns
Patterns
Literals
Literals
\(\( Matches (Matches ( \)\) Matches )Matches ) \xxx\xxx Matches the ASCII character expressed by the Matches the ASCII character expressed by the octal number xxx.octal number xxx.
"\50" matches "(" or chr (40)."\50" matches "(" or chr (40).
\xdd\xdd
Matches the ASCII character expressed by the hex number dd.Matches the ASCII character expressed by the hex number dd.
"\x28" matches "(" or chr (40). \}"\x28" matches "(" or chr (40). \}
\uxxxx\uxxxx
Matches the ASCII character expressed by the Matches the ASCII character expressed by the UNICODE xxxx.UNICODE xxxx.
24
Patterns
Character Classes
Character classes enable customized grouping by
putting expressions within [] braces.
A negated character class may be created by
placing ^ as the first character inside the [].
Also, a dash can be used to relate a scope of
characters.
For example, the regular expression
"[^a-zA-Z0-9]" matches everything except alphanumeric characters.
In addition, some common character sets are
Patterns
Patterns
Character Classes
Character Classes
[xyz][xyz] Match any one character enclosed in Match any one character enclosed in the character set.the character set.
"[a-e]" matches "b" "[a-e]" matches "b" in "basketball".in "basketball".
[^xyz][^xyz]
Match any one character not enclosed in the character set.Match any one character not enclosed in the character set.
"[^a-e]" matches "s" in "basketball". \xxx"[^a-e]" matches "s" in "basketball". \xxx
..
Match any character except \n.Match any character except \n.
\w\w
Match any word character.Match any word character.
EquivalenEquivalent to t to [a-zA-Z_0-9].[a-zA-Z_0-9].
\d\d
Match any digit.Match any digit.
EquivalenEquivalent to t to [0-9].[0-9].
\D\D
Match any non-digit.Match any non-digit.
Patterns
Patterns
Character Classes
Character Classes
\s\s Match any space character.Match any space character.
Equivalent to [ \t\r\n\v\f].Equivalent to [ \t\r\n\v\f].
\S\S
Match any non-space character.Match any non-space character.
Equivalent to [^ \t\r\n\v\f]. Equivalent to [^ \t\r\n\v\f].
Patterns
Patterns
Repetition
Repetition
Repetition allows multiple searchesRepetition allows multiple searches
on the clause within the regular on the clause within the regular expression.
expression.
By using repetition matching, weBy using repetition matching, we
can specify the number of times an can specify the number of times an element may be repeated in a
element may be repeated in a regular expression.
28
Patterns Repetiton
{x}
Match exactly x occurrences of a regular expression.
"\d{5}" matches 5 digits.
{x,}
Match x or more occurrences of a regular expression.
"\s{2,}" matches at least 2 space characters.
{x,y}
Matches x to y number of occurrences of a regular expression.
"\d{2,3}" matches at least 2 but no more than 3 digits.
?
Match zero or one occurrences. Equivalent to {0,1}.
"a\s?b" matches "ab" or "a b".
*
Match zero or more occurrences. Equivalent to {0,}.
+
29
Patterns
Alternation and Grouping
Alternation and grouping is used to
develop more complex regular expressions.
Using alternation and grouping
techniques can create intricate
clauses within a regular expression, and offer more flexibility and
Patterns
Patterns
Alternation and Grouping
Alternation and Grouping
()()
Grouping a clause to create a clause.Grouping a clause to create a clause.
May be nested.May be nested.
"(ab)?(c)" matches "abc" or "c"."(ab)?(c)" matches "abc" or "c".
| (pipe)| (pipe)
Alternation combines clauses into oneAlternation combines clauses into one
regular expression and then matches regular expression and then matches any of the individual clauses.
any of the individual clauses.
"(ab)|(cd)|(ef)" matches "ab" or "cd" or"(ab)|(cd)|(ef)" matches "ab" or "cd" or
"ef". "ef".
Patterns
Patterns
Backreferences
Backreferences
Backreferences enable theBackreferences enable the
programmer to refer back to a programmer to refer back to a
portion of the regular expression. portion of the regular expression.
This is done by use of parenthesisThis is done by use of parenthesis
and the backslash (\) character and the backslash (\) character followed by a single digit.
followed by a single digit.
The first parenthesis clause isThe first parenthesis clause is
referred by \1, the second by \2, referred by \1, the second by \2, etc.
32
Patterns
Backreferences
()\n
Matches a clause as numbered by the
left parenthesis.
"(\w+)\s+\1" matches any word that
occurs twice in a row, such as "hubba hubba."
Lab 13.1
Lab 13.1
Write a program to search the Write a program to search the followingfollowing files or directories in C:\WINNT,
files or directories in C:\WINNT, C:\WINNT\System32
C:\WINNT\System32
Files containing the lettersFiles containing the letters ““aa”” toto ““pp”” oror ““ss”” toto ““tt””
at least once, lowercase, Or the number 32 in at least once, lowercase, Or the number 32 in the end of the na
the end of the name (no extension).me (no extension).
Files with extension txt, created this Files with extension txt, created this monthmonth
name i.e
name i.e ““SeptemberSeptember”” (use DateValue function)(use DateValue function)
34
Lab 13.2
We have a button in an application
that behaves as the follow.
The label on it “show”.
When pressing on it, the label changes
to “hide”
Which Regular expression will fit to
Make sure to visit us
Tutorials Articles Proikects
And much more
www.AdvancedQTP.com