Saturday, 24 September 2011


What Is VBScript?
Microsoft Visual Basic Scripting Edition brings active scripting to a wide variety of environments, including Web client scripting in Microsoft Internet Explorer and Web server scripting in Microsoft Internet Information Service.
Easy to Use and Learn
If you already know Visual Basic or Visual Basic for Applications (VBA), VBScript will be very familiar. Even if you do not know Visual Basic, once you learn VBScript, you are on your way to programming with the whole family of Visual Basic languages. Although you can learn about VBScript in just these few Web pages, they do not teach you how to program. To learn programming, take a look at Step by Step books available from Microsoft Press.
Windows Script
VBScript talks to host applications using Windows Script. With Windows Script, browsers and other host applications do not require special integration code for each scripting component. Windows Script enables a host to compile scripts, obtain and call entry points, and manage the namespace available to the developer. With Windows Script, language vendors can create standard language run times for scripting. Microsoft will provide run-time support for VBScript. Microsoft is working with various Internet groups to define the Windows Script standard so that scripting engines can be interchangeable. Windows Script is used in Microsoft® Internet Explorer and in Microsoft® Internet Information Service.
VBScript in Other Applications and Browsers
As a developer, you can license VBScript source implementation at no charge for use in your products. Microsoft provides binary implementations of VBScript for the 32-bit Windows® API, the 16-bit Windows API, and the Macintosh®. VBScript is integrated with World Wide Web browsers. VBScript and Windows Script can also be used as a general scripting language in other applications.
Adding VBScript Code to an HTML Page
You can use the SCRIPT element to add VBScript code to an HTML page.
The <SCRIPT> Tag
VBScript code is written within paired <SCRIPT> tags. For example, a procedure to test a delivery date might appear as follows:
<SCRIPT LANGUAGE="VBScript">
<!--
   Function CanDeliver(Dt)
      CanDeliver = (CDate(Dt) - Now()) > 2
   End Function
-->
</SCRIPT>
Beginning and ending <SCRIPT> tags surround the code. The LANGUAGE attribute indicates the scripting language. You must specify the language because browsers can use other scripting languages. Notice that the CanDeliver function is embedded in comment tags (<!— and —>). This prevents browsers that don't understand the <SCRIPT> tag from displaying the code.
Since the example is a general function — it is not tied to any particular form control — you can include it in the HEAD section of the page:
<HTML>
<HEAD>
<TITLE>Place Your Order</TITLE>
<SCRIPT LANGUAGE="VBScript">
<!--
   Function CanDeliver(Dt)
      CanDeliver = (CDate(Dt) - Now()) > 2
   End Function
-->
</SCRIPT>
</HEAD>
<BODY>
...
You can use SCRIPT blocks anywhere in an HTML page. You can put them in both the BODY and HEAD sections. However, you will probably want to put all general-purpose scripting code in the HEAD section in order to keep all the code together. Keeping your code in the HEAD section ensures that all code is read and decoded before it is called from within the BODY section.
One notable exception to this rule is that you may want to provide inline scripting code within forms to respond to the events of objects in your form. For example, you can embed scripting code to respond to a button click in a form:
<HTML>
<HEAD>
<TITLE>Test Button Events</TITLE>
</HEAD>
<BODY>
<FORM NAME="Form1">
   <INPUT TYPE="Button" NAME="Button1" VALUE="Click">
   <SCRIPT FOR="Button1" EVENT="onClick" LANGUAGE="VBScript">
      MsgBox "Button Pressed!"
   </SCRIPT>
</FORM>
</BODY>
</HTML>
Most of your code will appear in either Sub or Function procedures and will be called only when specified by your code. However, you can write VBScript code outside procedures, but still within a SCRIPT block. This code is executed only once, when the HTML page loads. This allows you to initialize data or dynamically change the look of your Web page when it loads.
VBScript Features not in Visual Basic for Applications
The following table lists VBScript features not in Visual Basic for Applications.
Category
Feature/Keyword
Declarations
Miscellaneous
Objects
Script Engine Identification



Visual Basic for Applications Features Not In VBScript
The following table lists Visual Basic for Applications Features not in VBScript.
Category
Omitted Feature/Keyword
Array Handling
Option Base
Declaring arrays with lower bound <> 0
Collection
Add, Count, Item, Remove
Access to collections using ! character
Conditional Compilation
#Const
#If...Then...#Else
Control Flow
DoEvents
GoSub...Return, GoTo
On Error GoTo
On...GoSub, On...GoTo
Line numbers, Line labels
Conversion
CVar, CVDate
Str, Val
Data Types
All intrinsic data types except Variant
Type...End Type
Date/Time
Date statement, Time statement
DDE
LinkExecute, LinkPoke, LinkRequest, LinkSend
Debugging
Debug.Print
End, Stop
Declaration
Declare (for declaring DLLs)
Optional
ParamArray
Static
Error Handling
Erl
Error
Resume, Resume Next
File Input/Output
All traditional Basic file I/O
Financial
All financial functions
Object Manipulation
TypeOf
Objects
Clipboard
Collection
Operators
Like
Options
Deftype
Option Base
Option Compare
Option Private Module
Select Case
Expressions containing Is keyword or any comparison operators
Expressions containing a range of values using the To keyword.
Strings
Fixed-length strings
LSet, RSet
Mid Statement
StrConv
Using Objects
Collection access using !



VBScript Fundamentals

VBScript Data Types
VBScript Variables
VBScript Constants
VBScript Operators
Using Conditional Statements
Looping Through Code
VBScript Procedures
VBScript Coding Conventions

Introduction to Regular Expressions

The information contained in these pages is intended to provide an introduction to regular expressions in general.
While an attempt has been made to make each topic stand on it's own, much of the information contained in these topics relies upon the understanding of a previously introduced feature or concept. Therefore, it's recommended that you peruse these topics sequentially for the best overall understanding of the material.
The Introduction to Regular Expressions consists of the following individuals topics:
Regular Expressions
Early Beginnings
Uses for Regular Expressions
Regular Expression Syntax
Build a Regular Expression
Order of Precedence
Ordinary Characters
Special Characters
Non-Printable Characters
Character Matching
Quantifiers
Anchors
Alternation and Grouping
Backreferences
Visual Basic Scripting Edition

Regular Expressions
Unless you have worked with regular expressions before, the term and the concept may be unfamiliar to you. However, they may not be as unfamiliar as you think.
Think about how you search for files on your hard disk. You most likely use the ? and * characters to help find the files you're looking for. The ? character matches a single character in a file name, while the * matches zero or more characters. A pattern such as 'data?.dat' would find the following files:
data1.dat
data2.dat
datax.dat
dataN.dat
Using the * character instead of the ? character expands the number of files found. 'data*.dat' matches all of the following:
data.dat
data1.dat
data2.dat
data12.dat
datax.dat
dataXYZ.dat
While this method of searching for files can certainly be useful, it is also very limited. The limited ability of the ? and * wildcard characters give you an idea of what regular expressions can do, but regular expressions are much more powerful and flexible.
Visual Basic Scripting Edition

Early Beginnings
Regular expressions trace their ancestry back to early research on how the human nervous system works. Warren McCulloch and Walter Pitts, a pair of neuro-physiologists, developed a mathematical way of describing these neural networks.
In 1956, an mathematician named Stephen Kleene, building on the earlier work of McCulloch and Pitts, published a paper entitled, Representation of Events in Nerve Nets that introduced the concept of regular expressions. Regular expressions were expressions used to describe what he called "the algebra of regular sets". hence the term "regular expression."
Subsequently, his work found its way into some early efforts with computational search algorithms done by Ken Thompson, the principal inventor of Unix. The first practical application of regular expressions was in the Unix editor called qed.
And the rest, as they say, is history. Regular expressions have been an important part of text-based editors and search tools ever since.
Visual Basic Scripting Edition

Uses for Regular Expressions
In a typical search and replace operation, you must provide the exact text you are looking for. That technique may be adequate for simple search and replace tasks in static text, but it lacks flexibility and makes searching dynamic text difficult, if not impossible.
With regular expressions, you can:
  • Test for a pattern within a string. For example, you can test an input string to see if a telephone number pattern or a credit card number pattern occurs within the string. This is called data validation.
  • Replace text. You can use a regular expression to identify specific text in a document and either remove it completely or replace it with other text.
  • Extract a substring from a string based upon a pattern match. You can find specific text within a document or input field
For example, if you need to search an entire web site to remove some outdated material and replace some HTML formatting tags, you can use a regular expression to test each file to see if the material or the HTML formatting tags you are looking for exists in that file. That way, you can narrow down the affected files to only those that contain the material that has to be removed or changed. You can then use a regular expression to remove the outdated material, and finally, you can use regular expressions to search for and replace the tags that need replacing.
Another example of where a regular expression is useful occurs in a language that isn't known for its string-handling ability. VBScript, a subset of Visual Basic, has a rich set of string-handling functions. JScript, like C, does not. Regular expressions provide a significant improvement in string-handling for JScript. However, regular expressions may also be more efficient to use in VBScript as well, allowing you do perform multiple string manipulations in a single expression.
Visual Basic Scripting Edition

Regular Expression Syntax
A regular expression is a pattern of text that consists of ordinary characters (for example, letters a through z) and special characters, known as metacharacters. The pattern describes one or more strings to match when searching a body of text. The regular expression serves as a template for matching a character pattern to the string being searched.
Here are some examples of regular expression you might encounter:
JScript
VBScript
Matches
/^\[ \t]*$/
"^\[ \t]*$"
Match a blank line.
/\d{2}-\d{5}/
"\d{2}-\d{5}"
Validate an ID number consisting of 2 digits, a hyphen, and another 5 digits.
/<(.*)>.*<\/\1>/
"<(.*)>.*<\/\1>"
Match an HTML tag.
The following table contains the complete list of metacharacters and their behavior in the context of regular expressions:
Character
Description
\
Marks the next character as either a special character, a literal, a backreference, or an octal escape. For example, 'n' matches the character "n". '\n' matches a newline character. The sequence '\\' matches "\" and "\(" matches "(".
^
Matches the position at the beginning of the input string. If the RegExp object's Multiline property is set, ^ also matches the position following '\n' or '\r'.
$
Matches the position at the end of the input string. If the RegExp object's Multiline property is set, $ also matches the position preceding '\n' or '\r'.
*
Matches the preceding subexpression zero or more times. For example, zo* matches "z" and "zoo". * is equivalent to {0,}.
+
Matches the preceding subexpression one or more times. For example, 'zo+' matches "zo" and "zoo", but not "z". + is equivalent to {1,}.
?
Matches the preceding subexpression zero or one time. For example, "do(es)?" matches the "do" in "do" or "does". ? is equivalent to {0,1}
{n}
n is a nonnegative integer. Matches exactly n times. For example, 'o{2}' does not match the 'o' in "Bob," but matches the two o's in "food".
{n,}
n is a nonnegative integer. Matches at least n times. For example, 'o{2,}' does not match the "o" in "Bob" and matches all the o's in "foooood". 'o{1,}' is equivalent to 'o+'. 'o{0,}' is equivalent to 'o*'.
{n,m}
m and n are nonnegative integers, where n <= m. Matches at least n and at most m times. For example, "o{1,3}" matches the first three o's in "fooooood". 'o{0,1}' is equivalent to 'o?'. Note that you cannot put a space between the comma and the numbers.
?
When this character immediately follows any of the other quantifiers (*, +, ?, {n}, {n,}, {n,m}), the matching pattern is non-greedy. A non-greedy pattern matches as little of the searched string as possible, whereas the default greedy pattern matches as much of the searched string as possible. For example, in the string "oooo", 'o+?' matches a single "o", while 'o+' matches all 'o's.
.
Matches any single character except "\n". To match any character including the '\n', use a pattern such as '[.\n]'.
(pattern)
Matches pattern and captures the match. The captured match can be retrieved from the resulting Matches collection, using the SubMatches collection in VBScript or the $0$9 properties in JScript. To match parentheses characters ( ), use '\(' or '\)'.
(?:pattern)
Matches pattern but does not capture the match, that is, it is a non-capturing match that is not stored for possible later use. This is useful for combining parts of a pattern with the "or" character (|). For example, 'industr(?:y|ies) is a more economical expression than 'industry|industries'.
(?=pattern)
Positive lookahead matches the search string at any point where a string matching pattern begins. This is a non-capturing match, that is, the match is not captured for possible later use. For example 'Windows (?=95|98|NT|2000)' matches "Windows" in "Windows 2000" but not "Windows" in "Windows 3.1". Lookaheads do not consume characters, that is, after a match occurs, the search for the next match begins immediately following the last match, not after the characters that comprised the lookahead.
(?!pattern)
Negative lookahead matches the search string at any point where a string not matching pattern begins. This is a non-capturing match, that is, the match is not captured for possible later use. For example 'Windows (?!95|98|NT|2000)' matches "Windows" in "Windows 3.1" but does not match "Windows" in "Windows 2000". Lookaheads do not consume characters, that is, after a match occurs, the search for the next match begins immediately following the last match, not after the characters that comprised the lookahead.
x|y
Matches either x or y. For example, 'z|food' matches "z" or "food". '(z|f)ood' matches "zood" or "food".
[xyz]
A character set. Matches any one of the enclosed characters. For example, '[abc]' matches the 'a' in "plain".
[^xyz]
A negative character set. Matches any character not enclosed. For example, '[^abc]' matches the 'p' in "plain".
[a-z]
A range of characters. Matches any character in the specified range. For example, '[a-z]' matches any lowercase alphabetic character in the range 'a' through 'z'.
[^a-z]
A negative range characters. Matches any character not in the specified range. For example, '[^a-z]' matches any character not in the range 'a' through 'z'.
\b
Matches a word boundary, that is, the position between a word and a space. For example, 'er\b' matches the 'er' in "never" but not the 'er' in "verb".
\B
Matches a nonword boundary. 'er\B' matches the 'er' in "verb" but not the 'er' in "never".
\cx
Matches the control character indicated by x. For example, \cM matches a Control-M or carriage return character. The value of x must be in the range of A-Z or a-z. If not, c is assumed to be a literal 'c' character.
\d
Matches a digit character. Equivalent to [0-9].
\D
Matches a nondigit character. Equivalent to [^0-9].
\f
Matches a form-feed character. Equivalent to \x0c and \cL.
\n
Matches a newline character. Equivalent to \x0a and \cJ.
\r
Matches a carriage return character. Equivalent to \x0d and \cM.
\s
Matches any whitespace character including space, tab, form-feed, etc. Equivalent to [ \f\n\r\t\v].
\S
Matches any non-white space character. Equivalent to [^ \f\n\r\t\v].
\t
Matches a tab character. Equivalent to \x09 and \cI.
\v
Matches a vertical tab character. Equivalent to \x0b and \cK.
\w
Matches any word character including underscore. Equivalent to '[A-Za-z0-9_]'.
\W
Matches any nonword character. Equivalent to '[^A-Za-z0-9_]'.
\xn
Matches n, where n is a hexadecimal escape value. Hexadecimal escape values must be exactly two digits long. For example, '\x41' matches "A". '\x041' is equivalent to '\x04' & "1". Allows ASCII codes to be used in regular expressions.
\num
Matches num, where num is a positive integer. A reference back to captured matches. For example, '(.)\1' matches two consecutive identical characters.
\n
Identifies either an octal escape value or a backreference. If \n is preceded by at least n captured subexpressions, n is a backreference. Otherwise, n is an octal escape value if n is an octal digit (0-7).
\nm
Identifies either an octal escape value or a backreference. If \nm is preceded by at least nm captured subexpressions, nm is a backreference. If \nm is preceded by at least n captures, n is a backreference followed by literal m. If neither of the preceding conditions exists, \nm matches octal escape value nm when n and m are octal digits (0-7).
\nml
Matches octal escape value nml when n is an octal digit (0-3) and m and l are octal digits (0-7).
\un
Matches n, where n is a Unicode character expressed as four hexadecimal digits. For example, \u00A9 matches the copyright symbol (©).

Visual Basic Scripting Edition

Build a Regular Expression
Regular expressions are constructed in the same way that arithmetic expressions are created. That is, small expressions are combined using a variety of metacharacters and operators to create larger expressions.
You construct a regular expression by putting the various components of the expression pattern between a pair of delimiters. For JScript, the delimiters are a pair of forward slash (/) characters. For example:
/expression/
For VBScript, a pair of quotation marks ("") delimit regular expressions. For example:
"expression"
In both of the examples shown above, the regular expression pattern (expression) is stored in the Pattern property of the RegExp object.
The components of a regular expression can be individual characters, sets of characters, ranges of characters, choices between characters, or any combination of all of these components.
Visual Basic Scripting Edition

Order of Precedence
Once you have constructed a regular expression, it is evaluated much like an arithmetic expression, that is, it is evaluated from left to right and follows an order of precedence.
The following table illustrates, from highest to lowest, the order of precedence of the various regular expression operators:
Operator(s)
Description
\
Escape
(), (?:), (?=), []
Parentheses and Brackets
*, +, ?, {n}, {n,}, {n,m}
Quantifiers
^, $, \anymetacharacter
Anchors and Sequences
|
Alternation
Visual Basic Scripting Edition


Ordinary Characters
Ordinary characters consist of all those printable and non-printable characters that are not explicitly designated as metacharacters. This includes all upper- and lowercase alphabetic characters, all digits, all punctuation marks, and some symbols.
The simplest form of a regular expression is a single, ordinary character that matches itself in a searched string. For example, the single-character pattern 'A' matches the letter 'A' wherever it appears in the searched string. Here are some examples of single-character regular expression patterns:
/a/
/7/
/M/
The equivalent VBScript single-character regular expressions are:
"a"
"7"
"M"
You can combine a number of single characters together to form a larger expression. For example, the following JScript regular expression is nothing more than an expression created by combining the single-character expressions 'a', '7', and 'M'.
/a7M/
The equivalent VBScript expression is:
"a7M"
Notice that there is no concatenation operator. All that is required is that you just put one character after another.
Visual Basic Scripting Edition

Special Characters
There are a number of metacharacters that require special treatment when trying to match them. To match these special characters, you must first escape those characters, that is, precede them with a backslash character (\). The following table shows those special characters and their meanings:
Special Character
Comment
$
Matches the position at the end of an input string. If the RegExp object's Multiline property is set, $ also matches the position preceding '\n' or '\r'. To match the $ character itself, use \$.
( )
Marks the beginning and end of a subexpression. Subexpressions can be captured for later use. To match these characters, use \( and \).
*
Matches the preceding subexpression zero or more times. To match the * character, use \*.
+
Matches the preceding subexpression one or more times. To match the + character, use \+.
.
Matches any single character except the newline character \n. To match ., use \.
[
Marks the beginning of a bracket expression. To match [, use \[.
?
Matches the preceding subexpression zero or one time, or indicates a non-greedy quantifier. To match the ? character, use \?.
\
Marks the next character as either a special character, a literal, a backreference, or an octal escape. For example, 'n' matches the character 'n'. '\n' matches a newline character. The sequence '\\' matches "\" and '\(' matches "(".
^
Matches the position at the beginning of an input string except when used in a bracket expression where it negates the character set. To match the ^ character itself, use \^.
{
Marks the beginning of a quantifier expression. To match {, use \{.
|
Indicates a choice between two items. To match |, use \|.

Visual Basic Scripting Edition

Non-Printable Characters
There are a number of useful non-printing characters that must be used occasionally. The following table shows the escape sequences used to represent those non-printing characters:
Character
Meaning
\cx
Matches the control character indicated by x. For example, \cM matches a Control-M or carriage return character. The value of x must be in the range of A-Z or a-z. If not, c is assumed to be a literal 'c' character.
\f
Matches a form-feed character. Equivalent to \x0c and \cL.
\n
Matches a newline character. Equivalent to \x0a and \cJ.
\r
Matches a carriage return character. Equivalent to \x0d and \cM.
\s
Matches any whitespace character including space, tab, form-feed, etc. Equivalent to [\f\n\r\t\v].
\S
Matches any non-whitespace character. Equivalent to [^ \f\n\r\t\v].
\t
Matches a tab character. Equivalent to \x09 and \cI.
\v
Matches a vertical tab character. Equivalent to \x0b and \cK.

Visual Basic Scripting Edition

Character Matching
The period (.) matches any single printing or non-printing character in a string, except a newline character (\n). The following JScript regular expression matches 'aac', 'abc', 'acc', 'adc', and so on, as well as 'a1c', 'a2c', a-c', and a#c':
/a.c/
The equivalent VBScript regular expression is:
"a.c"
If you are trying to match a string containing a file name where a period (.) is part of the input string, you do so by preceding the period in the regular expression with a backslash (\) character. To illustrate, the following JScript regular expression matches 'filename.ext':
/filename\.ext/
For VBScript, the equivalent expression appears as follows:
"filename\.ext"
These expressions are still pretty limited. They only let you match any single character. Many times, it's useful to match specified characters from a list. For example, if you have an input text that contains chapter headings that are expressed numerically as Chapter 1, Chapter 2, etc, you might want to find those chapter headings.
Bracket Expressions
You can create a list of matching characters by placing one or more individual characters within square brackets ([ and ]). When characters are enclosed in brackets, the list is called a bracket expression. Within brackets, as anywhere else, ordinary characters represent themselves, that is, they match an occurrence of themselves in the input text. Most special characters lose their meaning when they occur inside a bracket expression. Here are some exceptions:
  • The ']' character ends a list if it's not the first item. To match the ']' character in a list, place it first, immediately following the opening '['.
  • The '\' character continues to be the escape character. To match the '\' character, use '\\'.
Characters enclosed in a bracket expression match only a single character for the position in the regular expression where the bracket expression appears. The following JScript regular expression matches 'Chapter 1', 'Chapter 2', 'Chapter 3', 'Chapter 4', and 'Chapter 5':
/Chapter [12345]/
To match those same chapter heading in VBScript, use the following:
"Chapter [12345]"
Notice that the word 'Chapter' and the space that follows are fixed in position relative to the characters within brackets. The bracket expression then, is used to specify only the set of characters that matches the single character position immediately following the word 'Chapter' and a space. That is the ninth character position.
If you want to express the matching characters using a range instead of the characters themselves, you can separate the beginning and ending characters in the range using the hyphen (-) character. The character value of the individual characters determines their relative order within a range. The following JScript regular expression contains a range expression that is equivalent to the bracketed list shown above.
/Chapter [1-5]/
The same expression for VBScript appears as follows:
"Chapter [1-5]"
When a range is specified in this manner, both the starting and ending values are included in the range. It is important to note that the starting value must precede the ending value in Unicode sort order.
If you want to include the hyphen character in your bracket expression, you must do one of the following:
  • Escape it with a backslash:
[\-]
  • Put the hyphen character at the beginning or the end of the bracketed list. The following expressions matches all lowercase letters and the hyphen:
·         [-a-z]
[a-z-]
  • Create a range where the beginning character value is lower than the hyphen character and the ending character value is equal to or greater than the hyphen. Both of the following regular expressions satisfy this requirement:
·         [!--]
[!-~]
You can also find all the characters not in the list or range by placing the caret (^) character at the beginning of the list. If the caret character appears in any other position within the list, it matches itself, that is, it has no special meaning. The following JScript regular expression matches chapter headings with numbers greater than 5':
/Chapter [^12345]/
For VBScript use:
"Chapter [^12345]"
In the examples shown above, the expression matches any digit character in the ninth position except 1, 2, 3, 4, or 5. So, for example, 'Chapter 7' is a match and so is 'Chapter 9'.
The same expressions above can be represented using the hyphen character (-). For JScript:
/Chapter [^1-5]/
or for VBScript:
"Chapter [^1-5]"
A typical use of a bracket expression is to specify matches of any upper- or lowercase alphabetic characters or any digits. The following JScript expression specifies such a match:
/[A-Za-z0-9]/
The equivalent expression for VBScript is:
"[A-Za-z0-9]"
Visual Basic Scripting Edition

Quantifiers
Sometimes, you don't know how many characters there are to match. In order to accommodate that kind of uncertainty, regular expressions support the concept of quantifiers. These quantifiers let you specify how many times a given component of your regular expression must occur for your match to be true.
The following table illustrates the various quantifiers and their meanings:
Character
Description
*
Matches the preceding subexpression zero or more times. For example, 'zo*' matches "z" and "zoo". * is equivalent to {0,}.
+
Matches the preceding subexpression one or more times. For example, 'zo+' matches "zo" and "zoo", but not "z". + is equivalent to {1,}.
?
Matches the preceding subexpression zero or one time. For example, 'do(es)?' matches the "do" in "do" or "does". ? is equivalent to {0,1}
{n}
n is a nonnegative integer. Matches exactly n times. For example, 'o{2}' does not match the 'o' in "Bob," but matches the two o's in "food".
{n,}
n is a nonnegative integer. Matches at least n times. For example, 'o{2,}' does not match the 'o' in "Bob" and matches all the o's in "foooood". 'o{1,}' is equivalent to 'o+'. 'o{0,}' is equivalent to 'o*'.
{n,m}
m and n are nonnegative integers, where n <= m. Matches at least n and at most m times. For example, 'o{1,3}' matches the first three o's in "fooooood". 'o{0,1}' is equivalent to 'o?'. Note that you cannot put a space between the comma and the numbers.
With a large input document, chapter numbers could easily exceed nine, so you need a way to handle two or three digit chapter numbers. Quantifiers give you that capability. The following JScript regular expression matches chapter headings with any number of digits:
/Chapter [1-9][0-9]*/
The following VBScript regular expression performs the identical match:
"Chapter [1-9][0-9]*"
Notice that the quantifier appears after the range expression. Therefore, it applies to the entire range expression that, in this case, specifies only digits from 0 through 9, inclusive.
The '+' quantifier is not used here because there does not necessarily need to be a digit in the second or subsequent position. The '?' character also is not used because it limits the chapter numbers to only two digits. You want to match at least one digit following 'Chapter' and a space character.
If you know that your chapter numbers are limited to only 99 chapters, you can use the following JScript expression to specify at least one, but not more than 2 digits.
/Chapter [0-9]{1,2}/
For VBScript, use the following regular expression:
"Chapter [0-9]{1,2}"
The disadvantage to the expression shown above is that if there is a chapter number greater than 99, it will still only match the first two digits. Another disadvantage is that somebody could create a Chapter 0 and it would match. Better JScript expressions for matching only two digits are the following:
/Chapter [1-9][0-9]?/
or
/Chapter [1-9][0-9]{0,1}/
For VBScript, the following expressions are equivalent:
"Chapter [1-9][0-9]?"
or
"Chapter [1-9][0-9]{0,1}"
The '*', '+', and '?' quantifiers are all what are referred to as greedy, that is, they match as much text as possible. Sometimes that's not at all what you want to happen. Sometimes, you just want a minimal match.
Say, for example, you are searching an HTML document for an occurrence of a chapter title enclosed in an H1 tag. That text appears in your document as:
<H1>Chapter 1 – Introduction to Regular Expressions</H1>
The following expression matches everything from the opening less than symbol (<) to the greater than symbol at the end of the closing H1 tag.
/<.*>/
The VBScript regular expression is:
"<.*>"
If all you really wanted to match was the opening H1 tag, the following, non-greedy expression matches only <H1>.
/<.*?>/
or
"<.*?>"
By placing the '?' after a '*', '+', or '?' quantifier, the expression is transformed from a greedy to a non-greedy, or minimal, match.
Visual Basic Scripting Edition

Anchors
So far, the examples you've seen have been concerned only with finding chapter headings wherever they occur. Any occurrence of the string 'Chapter' followed by a space, followed by a number, could be an actual chapter heading, or it could also be a cross-reference to another chapter. Since true chapter headings always appear at the beginning of a line, you'll need to devise a way to find only the headings and not find the cross-references.
Anchors provide that capability. Anchors allow you to fix a regular expression to either the beginning or end of a line. They also allow you to create regular expressions that occur either within a word or at the beginning or end of a word. The following table contains the list of regular expression anchors and their meanings:
Character
Description
^
Matches the position at the beginning of the input string. If the RegExp object's Multiline property is set, ^ also matches the position following '\n' or '\r'.
$
Matches the position at the end of the input string. If the RegExp object's Multiline property is set, $ also matches the position preceding '\n' or '\r'.
\b
Matches a word boundary, that is, the position between a word and a space.
\B
Matches a nonword boundary.
You cannot use a quantifier with an anchor. Since you cannot have more than one position immediately before or after a newline or word boundary, expressions such as '^*' are not permitted.
To match text at the beginning of a line of text, use the '^' character at the beginning of the regular expression. Don't confuse this use of the '^' with the use within a bracket expression. They're definitely not the same.
To match text at the end of a line of text, use the '$' character at the end of the regular expression.
To use anchors when searching for chapter headings, the following JScript regular expression matches a chapter heading with up to two following digits that occurs at the beginning of a line:
/^Chapter [1-9][0-9]{0,1}/
For VBScript the same regular expressions appears as:
"^Chapter [1-9][0-9]{0,1}"
Not only does a true chapter heading occur at the beginning of a line, it's also the only thing on the line, so it also must be at the end of a line as well. The following expression ensures that the match you've specified only matches chapters and not cross-references. It does so by creating a regular expression that matches only at the beginning and end of a line of text.
/^Chapter [1-9][0-9]{0,1}$/
For VBScript use:
"^Chapter [1-9][0-9]{0,1}$"
Matching word boundaries is a little different but adds a very important capability to regular expressions. A word boundary is the position between a word and a space. A non-word boundary is any other position. The following JScript expression matches the first three characters of the word 'Chapter' because they appear following a word boundary:
/\bCha/
or for VBScript:
"\bCha"
The position of the '\b' operator is critical here. If it's positioned at the beginning of a string to be matched, it looks for the match at the beginning of the word; if it's positioned at the end of the string, it looks for the match at the end of the word. For example, the following expressions match 'ter' in the word 'Chapter' because it appears before a word boundary:
/ter\b/
and
"ter\b"
The following expressions match 'apt' as it occurs in 'Chapter', but not as it occurs in 'aptitude':
/\Bapt/
and
"\Bapt"
That's because 'apt' occurs on a non-word boundary in the word 'Chapter' but on a word boundary in the word 'aptitude'. For the non-word boundary operator, position isn't important because the match isn't relative to the beginning or end of a word.

Visual Basic Scripting Edition

Alternation and Grouping
Alternation allows use of the '|' character to allow a choice between two or more alternatives. Expanding the chapter heading regular expression, you can expand it to cover more than just chapter headings. However, it's not as straightforward as you might think. When alternation is used, the largest possible expression on either side of the '|' character is matched. You might think that the following expressions for JScript and VBScript match either 'Chapter' or 'Section' followed by one or two digits occurring at the beginning and ending of a line:
/^Chapter|Section [1-9][0-9]{0,1}$/
"^Chapter|Section [1-9][0-9]{0,1}$"
Unfortunately, what happens is that the regular expressions shown above match either the word 'Chapter' at the beginning of a line, or 'Section' and whatever numbers follow that, at the end of the line. If the input string is 'Chapter 22', the expression shown above only matches the word 'Chapter'. If the input string is 'Section 22', the expression matches 'Section 22'. But that's not the intent here so there must be a way to make that regular expression more responsive to what you're trying to do and there is.
You can use parentheses to limit the scope of the alternation, that is, make sure that it applies only to the two words, 'Chapter' and 'Section'. However, parentheses are tricky as well, because they are also used to create subexpressions, something that's covered later in the section on subexpressions. By taking the regular expressions shown above and adding parentheses in the appropriate places, you can make the regular expression match either 'Chapter 1' or 'Section 3'.
The following regular expressions use parentheses to group 'Chapter' and 'Section' so the expression works properly. For JScript:
/^(Chapter|Section) [1-9][0-9]{0,1}$/
For VBScript:
"^(Chapter|Section) [1-9][0-9]{0,1}$"
These expressions work properly except that an interesting by-product occurs. Placing parentheses around 'Chapter|Section' establishes the proper grouping, but it also causes either of the two matching words to be captured for future use. Since there's only one set of parentheses in the expression shown above, there is only one captured submatch. This submatch can be referred to using the Submatches collection in VBScript or the $1-$9 properties of the RegExp object in JScript.
Sometimes capturing a submatch is desirable, sometimes it's not. In the examples shown above, all you really want to do is use the parentheses for grouping a choice between the words 'Chapter' or 'Section'. You don't necessarily want to refer to that match later. In fact, unless you really need to capture submatches, don't use them. Your regular expressions will be more efficient since they won't have to take the time and memory to store those submatches.
You can use '?:' before the regular expression pattern inside the parentheses to prevent the match from being saved for possible later use. The following modification of the regular expressions shown above provides the same capability without saving the submatch. For JScript:
/^(?:Chapter|Section) [1-9][0-9]{0,1}$/
For VBScript:
"^(?:Chapter|Section) [1-9][0-9]{0,1}$"
In addition to the '?:' metacharacters, there are two other non-capturing metacharacters used for something called lookahead matches. A positive lookahead, specified using ?=, matches the search string at any point where a matching regular expression pattern in parentheses begins. A negative lookahead, specified using '?!', matches the search string at any point where a string not matching the regular expression pattern begins.
For example, suppose you have a document containing references to Windows 3.1, Windows 95, Windows 98, and Windows NT. Suppose further that you need to update the document by finding all the references to Windows 95, Windows 98, and Windows NT and changing those reference to Windows 2000. You can use the following JScript regular expression, which is an example of a positive lookahead, to match Windows 95, Windows 98, and Windows NT:
/Windows(?=95 |98 |NT )/
To make the same match in VBScript, use the following:
"Windows(?=95 |98 |NT )"
Once the match is found, the search for the next match begins immediately following the matched text, not including the characters included in the look-ahead. For example, if the expressions shown above matched 'Windows 98', the search resumes after 'Windows' not after '98'.

Visual Basic Scripting Edition

Backreferences
One of the most important features of regular expressions is the ability to store a part of a matched pattern for later reuse. As you'll recall, placing parentheses around a regular expression pattern or part of a pattern causes that part of the expression to be stored into a temporary buffer. You can override the saving of that part of the regular expression using the non-capturing metacharacters '?:', '?=', or '?!'.
Each captured submatch is stored as it is encountered from left to right in a regular expressions pattern. The buffer numbers where the submatches are stored begin at 1 and continue up to a maximum of 99 subexpressions. Each different buffer can be accessed using '\n' where n is one or two decimal digits identifying a specific buffer.
One of the simplest, most useful applications of back references provides the ability to locate the occurrence of two identical words together in a text. Take the following sentence:
Is is the cost of of gasoline going up up?
As written, the sentence shown above clearly has a problem with several duplicated words. It would be nice to devise a way to fix that sentence without having to look for duplicates of every single word. The following JScript regular expression uses a single subexpression to do that.
/\b([a-z]+) \1\b/gi
The equivalent VBScript expression is:
"\b([a-z]+) \1\b"
The subexpression, in this case, is everything between parentheses. That captured expression includes one or more alphabetic characters, as specified by '[a-z]+'. The second part of the regular expression is the reference to the previously captured submatch, that is, the second occurrence of the word just matched by the parenthetical expression. '\1' is used to specified the first submatch. The word boundary Meta characters ensure that only separate words are detected. If they weren't, a phrase such as "is issued" or "this is" would be incorrectly identified by this expression.
In the JScript expression the global flag ('g') following the regular expression indicates that the expression is applied to as many matches as it can find in the input string. The case insensitivity ('i') flag at the end of the expression specifies the case insensitivity. The multiline flag specifies that potential matches may occur on either side of a newline character. For VBScript, the various flags cannot be set in the expression but must be explicitly set using properties of the RegExp object.
Using the regular expression shown above, the following JScript code can use the submatch information to replace an occurrence of two consecutive identical words in a string of text with a single occurrence of the same word:
var ss = "Is is the cost of of gasoline going up up?.\n";
var re = /\b([a-z]+) \1\b/gim;       //Create regular expression pattern.
var rv = ss.replace(re,"$1");   //Replace two occurrences with one.
The closest equivalent VBScript code appears as follows:
Dim ss, re, rv
ss = "Is is the cost of of gasoline going up up?." & vbNewLine
Set re = New RegExp
re.Pattern = "\b([a-z]+) \1\b"
re.Global = True
re.IgnoreCase = True
re.MultiLine = True
rv = re.Replace(ss,"$1")
In the VBScript code, notice that the global, case-insensitivity, and multiline flags are set using the appropriately named properties of the RegExp object.
The use of the $1 within the replace method refers to the first saved submatch. If you had more than one submatch, you'd refer to them consecutively by $2, $3, and so on.
Another way that backreferences can be used is to break down a Universal Resource Indicator (URI) into its component parts. Assume that you want to break down the following URI down to the protocol (ftp, http, etc), the domain address, and the page/path:
http://msdn.microsoft.com:80/scripting/default.htm
The following regular expressions provide that functionality. For JScript:
/(\w+):\/\/([^/:]+)(:\d*)?([^# ]*)/
For VBScript:
"(\w+):\/\/([^/:]+)(:\d*)?([^# ]*)"
The first parenthetical subexpression is designed to capture the protocol part of the web address. That subexpression matches any word that precedes a colon and two forward slashes. The second parenthetical subexpression captures the domain address part of the address. That subexpression matches any sequence of characters that does not include '^', '/', or ':' characters. The third parenthetical subexpression captures a website port number, if one is specified. That subexpression matches zero or more digits following a colon. And finally, the fourth parenthetical subexpression captures the path and/or page information specified by the web address. That subexpression matches one or more characters other than '#' or the space character.
Applying the regular expression to the URI shown above, the submatches contain the following:
  • RegExp.$1 contains "http"
  • RegExp.$2 contains "msdn.microsoft.com"
  • RegExp.$3 contains ":80"
  • RegExp.$4 contains "/scripting/default.htm"




Dictionary Object

See Also

FileSystemObject Object | TextStream Object
Language
  • JScript
  • VBScript
  • Show All
Object that stores data key, item pairs.

Remarks

A Dictionary object is the equivalent of a PERL associative array. Items can be any form of data, and are stored in the array. Each item is associated with a unique key. The key is used to retrieve an individual item and is usually a integer or a string, but can be anything except an array.
The following code illustrates how to create a Dictionary object:
[JScript]
var y = new ActiveXObject("Scripting.Dictionary");
y.add ("a", "test");
if (y.Exists("a"))
   document.write("true");
...
[VBScript]
Dim d   ' Create a variable.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"   ' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
...

Methods

Add Method (Dictionary) | Exists Method | Items Method | Keys Method | Remove Method | RemoveAll Method

Properties

Count Property | Item Property | Key Property

See Also

FileSystemObject Object | TextStream Object





Count Property

See Also

CompareMode Property | Item Property | Key Property
Applies To: Dictionary Object | Drives Collection | Files Collection | Folders Collection
Language
  • JScript
  • VBScript
  • Show All
Returns the number of items in a collection or Dictionary object. Read-only.
object.Count
The object is always the name of one of the items in the Applies To list.

Remarks

The following code illustrates use of the Count property:
[JScript]
function CountDemo()
{
   var a, d, i, s;                 // Create some variables.
   d = new ActiveXObject("Scripting.Dictionary");   
   d.Add ("a", "Athens");          // Add some keys and items.
   d.Add ("b", "Belgrade");
   d.Add ("c", "Cairo");
   a = (new VBArray(d.Keys()));    // Get the keys.
   s = "";
   for (i = 0; i < d.Count; i++)   //Iterate the dictionary.
   {
      s += a.getItem(i) + " - " + d(a.getItem(i)) + "<br>";
   }
   return(s);                      // Return the results.
}
[VBScript]
Function ShowKeys
   Dim a, d, i, s   ' Create some variables.
   Set d = CreateObject("Scripting.Dictionary")
   d.Add "a", "Athens"   ' Add some keys and items.
   d.Add "b", "Belgrade"
   d.Add "c", "Cairo"
   a = d.Keys   ' Get the keys.
   For i = 0 To d.Count -1 ' Iterate the array.
      s = s & a(i) & "<BR>" ' Create return string.
   Next
   ShowKeys = s
End Function

See Also

CompareMode Property | Item Property | Key Property
Applies To: Dictionary Object | Drives Collection | Files Collection | Folders Collection




Item Property

See Also

CompareMode Property | Count Property | Key Property
Applies To: Dictionary Object | Drives Collection | Files Collection | Folders Collection
Language
  • JScript
  • VBScript
  • Show All
Sets or returns an item for a specified key in a Dictionary object. For collections, returns an item based on the specified key. Read/write.
object.Item(key)[ = newitem]

Arguments

object
Required. Always the name of a collection or Dictionary object.
key
Required. Key associated with the item being retrieved or added.
newitem
Optional. Used for Dictionary object only; no application for collections. If provided, newitem is the new value associated with the specified key.

Remarks

If key is not found when changing an item, a new key is created with the specified newitem. If key is not found when attempting to return an existing item, a new key is created and its corresponding item is left empty.
The following example illustrates the use of the Item property.
[JScript]
function DicTest(keyword)
{
   var a, d; 
   d = new ActiveXObject("Scripting.Dictionary");
   d.Add("a", "Athens");
   d.Add("b", "Belgrade");
   d.Add("c", "Cairo");
   a = d.Item(keyword);
   return(a);
}
[VBScript]
Function ItemDemo
   Dim d   ' Create some variables.
   Set d = CreateObject("Scripting.Dictionary")
   d.Add "a", "Athens"   ' Add some keys and items.
   d.Add "b", "Belgrade"
   d.Add "c", "Cairo"
   ItemDemo = d.Item("c")   ' Get the item.
End Function

See Also

CompareMode Property | Count Property | Key Property
Applies To: Dictionary Object | Drives Collection | Files Collection | Folders Collection




Key Property

See Also

CompareMode Property | Count Property | Item Property
Applies To: Dictionary Object
Language
  • JScript
  • VBScript
  • Show All
Sets a key in a Dictionary object.
object.Key(key) = newkey

Arguments

object
Required. Always the name of a Dictionary object.
key
Required. Key value being changed.
newkey
Required. New value that replaces the specified key.

Remarks

If key is not found when changing a key, a new key is created and its associated item is left empty.
The following example illustrates the use of the Key property:
[JScript]
var d;
d = new ActiveXObject("Scripting.Dictionary");
 
function AddStuff()
{
   var a;
   d.Add("a", "Athens");
   d.Add("b", "Belgrade");
   d.Add("c", "Cairo");
}
 
function ChangeKey(oldkey, newkey)
{
   var s;
   d.Key("c") = "Ca";
   s = "Key " + oldkey + " changed to " + newkey;
   return(s);
}
[VBScript]
Function DicDemo
   Dim d   ' Create some variables.
   Set d = CreateObject("Scripting.Dictionary")
   d.Add "a", "Athens"   ' Add some keys and items.
   d.Add "b", "Belgrade"
   d.Add "c", "Cairo"
   d.Key("c") = "d"   ' Set key for "c" to "d".
   DicDemo = d.Item("d")   ' Return associate item.
End Function

See Also

CompareMode Property | Count Property | Item Property
Applies To: Dictionary Object




Add Method (Dictionary)

See Also

Add Method (Folders) | Exists Method | Items Method | Keys Method | Remove Method | RemoveAll Method
Applies To: Dictionary Object
Language
  • JScript
  • VBScript
  • Show All
Adds a key and item pair to a Dictionary object.
object.Add (key, item)

Arguments

object
Required. Always the name of a Dictionary object.
key
Required. The key associated with the item being added.
item
Required. The item associated with the key being added.

Remarks

An error occurs if the key already exists.
The following example illustrates the use of the Add method.
[JScript]
var d;
d = new ActiveXObject("Scripting.Dictionary");
d.Add("a", "Athens");
d.Add("b", "Belgrade");
d.Add("c", "Cairo");
[VBScript]
Dim d   ' Create a variable.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"   ' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"

See Also

Add Method (Folders) | Exists Method | Items Method | Keys Method | Remove Method | RemoveAll Method
Applies To: Dictionary Object





Exists Method

See Also

Add Method (Dictionary) | Items Method | Keys Method | Remove Method | RemoveAll Method
Applies To: Dictionary Object
Language
  • JScript
  • VBScript
  • Show All
Returns true if a specified key exists in the Dictionary object, false if it does not.
object.Exists(key)

Arguments

object
Required. Always the name of a Dictionary object.
key
Required. Key value being searched for in the Dictionary object.

Remarks

The following example illustrates the use of the Exists method.
[JScript]
function keyExists(k)
{
   var fso, s = "";
   d = new ActiveXObject("Scripting.Dictionary");
   d.Add("a", "Athens");
   d.Add("b", "Belgrade");
   d.Add("c", "Cairo");
   if (d.Exists(k))
      s += "Specified key exists.";
   else 
      s += "Specified key doesn't exist.";
   return(s);
}
[VBScript]
Function KeyExistsDemo
   Dim d, msg   ' Create some variables.
   Set d = CreateObject("Scripting.Dictionary")
   d.Add "a", "Athens"   ' Add some   keys and items.
   d.Add "b", "Belgrade"
   d.Add "c", "Cairo"
   If d.Exists("c") Then
      msg = "Specified key exists."
   Else
      msg = "Specified key doesn't exist."
   End If
   KeyExistsDemo = msg
End Function

See Also

Add Method (Dictionary) | Items Method | Keys Method | Remove Method | RemoveAll Method
Applies To: Dictionary Object





Add Method (Dictionary)

See Also

Add Method (Folders) | Exists Method | Items Method | Keys Method | Remove Method | RemoveAll Method
Applies To: Dictionary Object
Language
  • JScript
  • VBScript
  • Show All
Adds a key and item pair to a Dictionary object.
object.Add (key, item)

Arguments

object
Required. Always the name of a Dictionary object.
key
Required. The key associated with the item being added.
item
Required. The item associated with the key being added.

Remarks

An error occurs if the key already exists.
The following example illustrates the use of the Add method.
[JScript]
var d;
d = new ActiveXObject("Scripting.Dictionary");
d.Add("a", "Athens");
d.Add("b", "Belgrade");
d.Add("c", "Cairo");
[VBScript]
Dim d   ' Create a variable.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"   ' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"

See Also

Add Method (Folders) | Exists Method | Items Method | Keys Method | Remove Method | RemoveAll Method
Applies To: Dictionary Object




Exists Method

See Also

Add Method (Dictionary) | Items Method | Keys Method | Remove Method | RemoveAll Method
Applies To: Dictionary Object
Language
  • JScript
  • VBScript
  • Show All
Returns true if a specified key exists in the Dictionary object, false if it does not.
object.Exists(key)

Arguments

object
Required. Always the name of a Dictionary object.
key
Required. Key value being searched for in the Dictionary object.

Remarks

The following example illustrates the use of the Exists method.
[JScript]
function keyExists(k)
{
   var fso, s = "";
   d = new ActiveXObject("Scripting.Dictionary");
   d.Add("a", "Athens");
   d.Add("b", "Belgrade");
   d.Add("c", "Cairo");
   if (d.Exists(k))
      s += "Specified key exists.";
   else 
      s += "Specified key doesn't exist.";
   return(s);
}
[VBScript]
Function KeyExistsDemo
   Dim d, msg   ' Create some variables.
   Set d = CreateObject("Scripting.Dictionary")
   d.Add "a", "Athens"   ' Add some   keys and items.
   d.Add "b", "Belgrade"
   d.Add "c", "Cairo"
   If d.Exists("c") Then
      msg = "Specified key exists."
   Else
      msg = "Specified key doesn't exist."
   End If
   KeyExistsDemo = msg
End Function

See Also

Add Method (Dictionary) | Items Method | Keys Method | Remove Method | RemoveAll Method
Applies To: Dictionary Object




Items Method

See Also

Add Method (Dictionary) | Exists Method | Keys Method | Remove Method | RemoveAll Method
Applies To: Dictionary Object
Language
  • JScript
  • VBScript
  • Show All
Returns an array containing all the items in a Dictionary object.
object.Items( )
The object is always the name of a Dictionary object.

Remarks

The following code illustrates use of the Items method:
[JScript]
function ItemsDemo()
{
   var a, d, i, s;                  // Create some variables.
   d = new ActiveXObject("Scripting.Dictionary");  
   d.Add ("a", "Athens");              // Add some keys and items.
   d.Add ("b", "Belgrade");
   d.Add ("c", "Cairo");
   a = (new VBArray(d.Items())).toArray();   // Get the items.
   s = "";
   for (i in a)                  // Iterate the dictionary.
   {
      s += a[i] + "<br>";
   }
   return(s);                     // Return the results.
}
[VBScript]
Function DicDemo
   Dim a, d, i, s   ' Create some variables.
   Set d = CreateObject("Scripting.Dictionary")
   d.Add "a", "Athens"   ' Add some keys and items.
   d.Add "b", "Belgrade"
   d.Add "c", "Cairo"
   a = d.Items   ' Get the items.
   For i = 0 To d.Count -1 ' Iterate the array.
      s = s & a(i) & "<BR>" ' Create return string.
   Next
   DicDemo = s
End Function

See Also

Add Method (Dictionary) | Exists Method | Keys Method | Remove Method | RemoveAll Method
Applies To: Dictionary Object




Keys Method

See Also

Add Method (Dictionary) | Exists Method | Items Method | Remove Method | RemoveAll Method
Applies To: Dictionary Object
Language
  • JScript
  • VBScript
  • Show All
Returns an array containing all existing keys in a Dictionary object.
object.Keys( )
The object is always the name of a Dictionary object.

Remarks

The following code illustrates use of the Keys method:
[JScript]
function KeysDemo()
{
   var a, d, i, s;                  // Create some variables.
   d = new ActiveXObject("Scripting.Dictionary");  
   d.Add ("a", "Athens");              // Add some keys and items.
   d.Add ("b", "Belgrade");
   d.Add ("c", "Cairo");
   a = (new VBArray(d.Keys())).toArray();   // Get the keys.
   s = "";
   for (i in a)                  // Iterate the dictionary.
   {
      s += a[i] + " - " + d(a[i]) + "<br>";
   }
   return(s);                     // Return the results.
}
[VBScript]
Function DicDemo
   Dim a, d, i   ' Create some variables.
   Set d = CreateObject("Scripting.Dictionary")
   d.Add "a", "Athens"   ' Add some keys and items.
   d.Add "b", "Belgrade"
   d.Add "c", "Cairo"
   a = d.Keys   ' Get the keys.
   For i = 0 To d.Count -1 ' Iterate the array.
      s = s & a(i) & "<BR>" ' Return results.
   Next
   DicDemo = s
End Function

See Also

Add Method (Dictionary) | Exists Method | Items Method | Remove Method | RemoveAll Method
Applies To: Dictionary Object





Remove Method

See Also

Add Method (Dictionary) | Exists Method | Items Method | Keys Method | RemoveAll Method
Applies To: Dictionary Object
Language
  • JScript
  • VBScript
  • Show All
Removes a key, item pair from a Dictionary object.
object.Remove(key)

Arguments

object
Required. Always the name of a Dictionary object.
key
Required. Key associated with the key, item pair you want to remove from the Dictionary object.

Remarks

An error occurs if the specified key, item pair does not exist.
The following code illustrates use of the Remove method:
[JScript]
var a, d, i, s;              // Create some variables.
d = new ActiveXObject("Scripting.Dictionary");  
d.Add ("a", "Athens");       // Add some keys and items.
d.Add ("b", "Belgrade");
d.Add ("c", "Cairo");
...
d.Remove("b");               // Remove second pair.
[VBScript]
Dim a, d   ' Create some variables.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"   ' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
...
d.Remove("b")   ' Remove second pair.

See Also

Add Method (Dictionary) | Exists Method | Items Method | Keys Method | RemoveAll Method
Applies To: Dictionary Object







RemoveAll Method

See Also

Add Method (Dictionary) | Exists Method | Items Method | Keys Method | Remove Method
Applies To: Dictionary Object
Language
  • JScript
  • VBScript
  • Show All
The RemoveAll method removes all key, item pairs from a Dictionary object.
object.RemoveAll( )
The object is always the name of a Dictionary object.

Remarks

The following code illustrates use of the RemoveAll method:
[JScript]
var a, d, i;             // Create some variables.
d = new ActiveXObject("Scripting.Dictionary");
d.Add ("a", "Athens");   // Add some keys and items.
d.Add ("b", "Belgrade");
d.Add ("c", "Cairo");
...
d.RemoveAll( );       // Clear the dictionary.
[VBScript]
Dim a, d, i   ' Create some variables.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"   ' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
...
a = d.RemoveAll   ' Clear the dictionary.

See Also

Initialize Event

See Also

Class Object | Class Statement | Terminate Event
Applies To: Class Object

Requirements

Version 5
Occurs when an instance of the associated class is created.
Private Sub Class_Initialize()
   statements
End Sub
The statements part consists of zero or more code statements to be run when the class is initialized.

Remarks

The following example illustrates the use of the Initialize event.
Class TestClass
   Private Sub Class_Initialize   ' Setup Initialize event.
      MsgBox("TestClass started")
   End Sub
   Private Sub Class_Terminate   ' Setup Terminate event.
      MsgBox("TestClass terminated")
   End Sub
End Class
 
Set X = New TestClass   ' Create an instance of TestClass.
Set X = Nothing   ' Destroy the instance.

Requirements

Version 5

See Also

Class Object | Class Statement | Terminate Event
Applies To: Class Object




Terminate Event

See Also

Class Object | Class Statement | Initialize Event
Applies To: Class Object

Requirements

Version 5
Occurs when an instance of the associated class is terminated.
Private Sub Class_Terminate()
   statements
End Sub
The statements part consists of zero or more code statements to be run when the class is initialized.

Remarks

The following example illustrates the use of the Terminate event.
Class TestClass
   Private Sub Class_Initialize   ' Setup Initialize event.
      MsgBox("TestClass started")
   End Sub
    Private Sub Class_Terminate   ' Setup Terminate event.
      MsgBox("TestClass terminated")
   End Sub
End Class
Set X = New TestClass   ' Create an instance of TestClass.
Set X = Nothing   ' Destroy the instance.



0 comments:

Post a Comment

Bookmark Us

Delicious Digg Facebook Favorites More Stumbleupon Twitter