OReilly VBScript In A Nutshell 2nd Edition Mar 2003 ISBN 0596004885

46 80 0
OReilly VBScript In A Nutshell 2nd Edition Mar 2003 ISBN 0596004885

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

RegExp.Global Property Data Type Boolean Description Determines whether the search for a pattern string should match all occurrences in the search string or just the first one Rules at a Glance A search will attempt to locate only the first occurrence of the pattern string in a search string; that is, the default value of the Global property is False If you want to search for all occurrences of the pattern string in the search string, you must set the Global property to True Programming Tips and Gotchas If you're interested only in determining whether the pattern string exists in the search string, there's no point in overriding the Global property's default value of False See Also Matches Collection Object, Match Object, RegExp Object Matches Collection Object Description The collection of zero or more Match objects returned by the RegExp object's Execute method; each Match object allows you to identify and manipulate one of the strings found by the regular expression Createable No Returned by RegExp.Execute Method Properties The Matches collection object supports the following two properties: Count Data Type: Long Indicates the number of objects in the collection A value of zero indicates that the collection is empty The property is read-only Item Syntax: Matches.Item(index) Data Type: Match object Returns a particular Match object based on index, its ordinal position in the collection Matches is a zero-based collection; that is, its first member is at ordinal position 0, while its last member is at ordinal position Matches.Count 1 Example See the example for the Match object See Also Match Object, RegExp Object, RegExp.Execute Method Match Object Description A member of the Matches collection that is returned by a call to the RegExp object's Execute method, the Match object represents a successful regular expression match Createable No Returned by Matches.Item property Properties The Match object supports the following three properties: FirstIndex Data Type: Long Indicates the position in the original search string where the regular expression match occurred The first character in the search string is at position 1 Length Data Type: Long Indicates the number of characters in the match found in the search string This is also the number of characters in the Match object's Value property Value Data Type: String The text of the match found in the search string Example Since the RegExp object's Execute method searches only a string, the example program writes the filename of each file in the Windows directory to a variable named strNames Each filename is preceded by two spaces The RegExp object's Execute method is then called to search for every filename beginning with the letter "B" (the regular expression searches for two spaces followed by a "B") The Matches collection is then iterated so that each filename can be extracted from strNames and displayed in a message box: Dim fs, root, dir, fls, fl Dim rexp Dim mtchs, mtch Dim strNames, strMsg Dim lStartPos strNames = " " Set fs = CreateObject("Scripting.FileSystemObject") Set root = fs.Drives("C").RootFolder Set dir = root.SubFolders("Windows") Set fls = dir.Files For Each fl In fls strNames = strNames & fl.Name & " " Next MsgBox Len(strNames) Set rexp = New RegExp rexp.Global = True rexp.Pattern = "(\s\sB)" Set mtchs = rexp.Execute(strNames) For Each mtch In mtchs lStartPos = mtch.FirstIndex + 2 strMsg = strMsg & Mid(strNames, lStartPos, _ InStr(lStartPos, strNames, " ") - lStartPos + 1) & Next MsgBox strMsg See Also RegExp Object RegExp Object Description The RegExp object provides support for regular expression matchingfor the ability to search strings for substrings matching general or specific patterns In order to conduct a pattern search, you must first instantiate the regular expression object, with code like the following: Dim oRegExp ' Instance of RegExp object Set oRegExp = New RegExp To conduct a search using the RegExp object, do the following: Determine whether the search should be case-sensitive Determine whether all instances or just the first instance of the substring should be returned Supply the pattern string that you want to find Provide a string that the RegExp object is to search The RegExp object allows you to search for a substring that matches your pattern string in any of three ways: You can determine whether a pattern match is found in the string You can return one or all of the occurrences of the matching substrings In this case, results are returned in Match objects within the Matches collection You can replace all substrings matching the pattern string with another string Properties The RegExp object supports the three properties shown in the following table Each is documented in depth in its own section in the Language Reference Property name Description Global Indicates whether to search for all occurrences of the pattern string or just for the first one IgnoreCase Indicates whether the pattern search is case-sensitive Pattern Indicates the pattern string to search for Methods The RegExp object supports the three methods shown in the following table Each is documented in depth in its own section in the Language Reference Method name Description Execute Returns a Matches collection containing information about the substrings in a larger string that match a pattern string Replace Replaces all substrings in a larger string that match a pattern string with a second string Test Indicates whether the search of a string has succeeded in finding a pattern match VBA/VBScript Differences The RegExp object, which was introduced to give VBScript comparable features to JScript, is exclusive to VBScript; it does not exist as a core part of the VBA language However, the RegExp object is implemented as a member of the VBScript.dll library and can be added to any Visual Basic project It is listed in the References dialog (which is available by selecting the References option from the Visual Basic Project menu) as "Microsoft VBScript Regular Expressions." See Also InStr, InStrB Functions, InstrRev Function, Match Object, Matches Collection Object RegExp.Execute Method Syntax RegExp.Execute(string) string Use: Required Data Type: String The string to be searched Return Value A Matches collection containing one or more Match objects Description Performs a regular expression search against string and returns the results in the Matches collection Rules at a Glance The method searches string using the RegExp object's Pattern property The results are returned in the Matches collection, which is a collection of Match objects If the search finds no matches, the Matches collection is empty If length is 0, a zero-length string (" ") is returned If length is greater than the length of string, string is returned If length is less than 0 or Null, the function generates runtime error 5, "Invalid procedure call or argument," and runtime error 94, "Invalid use of Null," respectively If string contains Null, Left returns Null Left processes strings of characters; LeftB is used to process binary data Programming Tips and Gotchas Use the Len function to determine the overall length of string When you use the LeftB function with byte data, length specifies the number of bytes to return VBScript/VB & VBA Differences There are no Left$ or LeftB$ functions available in VBScript See Also Len, LenB Functions, Mid, MidB Functions, Right, RightB Functions Mid, MidB Functions Syntax Mid(string, start[, length]) string Use: Required Data Type: String The expression from which to return a substring start Use: Required Data Type: Long The starting position of the substring length Use: Optional Data Type: Long The length of the substring Return Value A String Description Returns a substring of a specified length from within a given string Rules at a Glance If string contains a Null, Mid returns Null If start is more than the length of string, a zero-length string is returned If start is less than zero, error 5, "Invalid procedure call or argument," is generated If length is omitted or is greater than the length of string, all characters from start to the end of string are returned The MidB version of the Mid function is used with byte data held within a string When using MidB, both start and length refer to numbers of bytes as opposed to numbers of characters Example The following example is a function that parses a string passed to it as a parameter and writes each word to a dynamic array Note the use of the InStr function to determine the position of a space, which in this case is the character that can terminate a word: Public Function ParseString(strString) Dim arr( ) Dim intStart, intEnd, intStrLen, intCtr intCtr = 0 intStart = 1 intStrLen = Len(strString) Redim Preserve arr(10) Do While intStart > 0 intEnd = InStr(intStart, strString, " ") - 1 If intEnd UBound(arr) Then Redim Preserve arr(UBound(arr)+10) End If arr(intCtr) = Mid(strString, intStart, _ intEnd - intStart + 1) intStart = intEnd + 2 intCtr = intCtr + 1 If intStart > intStrLen Then intStart = 0 Loop ParseString = arr End Function Programming Tips and Gotchas Use the Len function to determine the total length of string Use InStr to determine the starting point of a given substring within another string VBA/VBScript Differences Because it does not support strong typing, VBScript does not support the Mid$ and MidB$ functions, which explicitly return a string, rather than a String VBA supports the Mid statement, which allows a portion of the string to be replaced with another substring For example: Dim strPhrase As String strPhrase = "This will be the day." Mid(strPhrase, 3, 2) = "at" changes the value of strPhrase to "That will be day." This usage of Mid in statement form is not supported by VBScript See Also Left, LeftB Functions; Len, LenB Functions; Right, RightB Functions Right, RightB Functions Syntax Right(string, length) string Use: Required Data Type: String The string to be processed length Use: Required Data Type: Long The number of characters to return from the right of the string Return Value A String Description Returns a string containing the right-most length characters of string Rules at a Glance If length is 0, a zero-length string (" ") is returned If length is greater than the length of string, string is returned If length is less than zero or is Null, an error is generated If string contains a Null, Right returns Null Example The following function assumes it's passed either a filename or a complete path and filename, and returns the filename from the end of the string: Private Function ParseFileName(strFullPath) Dim lngPos, lngStart Dim strFilename lngStart = 1 Do lngPos = InStr(lngStart, strFullPath, "\") If lngPos = 0 Then strFilename = Right(strFullPath, Len(strFullPath) - lngSt Else lngStart = lngPos + 1 End If Loop While lngPos > 0 ParseFileName = strFilename End Function Programming Tips and Gotchas Use the Len function to determine the total length of string When you use the RightB function with byte data, length specifies the number of bytes to return VB/VBA Differences Because VBScript doesn't support strong typing, it does not support the Right$ and RightB$ functions, which explicitly return a data type See Also Len, LenB Functions, Left, LeftB Functions StrComp Function Syntax StrComp(string1, string2[, compare]) string1 Use: Required Data Type: String Any string expression string2 Use: Required Data Type: String Any string expression compare Use: Optional Data Type: Integer constant The type of string comparison to perform Return Value An Integer Description Determines whether two strings are equal and which of two strings is greater Rules at a Glance The following intrinsic constants are available as the settings for compare: Constant Value Comparison to perform vbBinaryCompare Binary (default) vbTextCompare Textual If compare isn't specified, its value defaults to vbBinaryCompare In other words, the comparison of string1 and string2 is case-sensitive This table describes the possible return values from the StrComp function: Scenario Return value string1 < string2 -1 string1 = string2 string1 > string2 string1 or string2 is Null Null Programming Tips and Gotchas If you just need to know whether string1 is greater than string2 (or vice versa), couldn't you simply use the < or > comparison operators? When you're dealing with strings of characters, VBScript sees each character as a number Simply using the comparison operators therefore compares the numerical value of one string with the other Take this scenario: Dim sString1 Dim sString2 sString1 = "hello world" sString2 = "HELLO WORLD" Subjectively, because of the significance of uppercase letters in text, we'd probably say that sString2 is greater than sString1 But VBScript sees these strings as a series of Unicode numbers, and because uppercase characters have a lower Unicode number than lowercase numbers, the lowercase string (sString1) is greater This is similar to how the default StrComp option vbBinaryCompare operatescomparing the Unicode numbers of each string at binary level The sort order is derived from the international binary representations of the characters vbCompareText performs a case-insensitive search, which means that it ignores the difference between upper- and lowercase characters It also means that it will equate different representations of the same character in some Far Eastern character sets vbCompareText, in other words, indicates a case-insensitive textual sort order as determined by the user's locale Even performing a simple single comparison like: If UCase(sString1) < UCase(sString2) Then shows a performance hit of about 30 percent over the much more elegant and efficient StrComp function call: If StrComp(sString1,sString2, vbTextCompare) = -1 Then The former version, though, is easier to read and makes the code self-documenting Len, LenB Functions Syntax Len(string | varname) LenB(string | varname) string Use: Required Data Type: String A valid string literal or string expression varname Use: Required Data Type: Any except Object A valid variable name Return Value Long Description Len returns the number of characters in a string or variable LenB returns the number of bytes required to store a string in memory Rules at a Glance string and varname are mutually exclusive; that is, you must specify either string or varname, but not both If either string or varname is Null, Len and LenB return Null You can't use Len or LenB with an object variable If varname is an array, you must also specify a valid subscript In other words, Len and LenB can't determine the total number of elements in or the total size of an array To determine the size of an array, use the LBound and UBound functions Programming Tips and Gotchas Nonstring data is treated the same as strings when passed to the Len and LenB functions For example, in the code: Dim number number = 100 WScript.Echo Len(number) the Len function returns 3, since that is the number of characters in the value of number LenB is intended to work with string data, and returns the number of bytes required to store that string If a nonstring data type is passed to the LenB function, its value is first converted to a string before its length is determined VBA/VBScript Differences Although the Len and LenB functions handle strings identically in VBA and VBScript, they handle non-string data types quite differently Len and LenB in VBA reports the number of bytes required to store the non-string data type in memory In contrast, in VBScript, Len reports the number of characters in the string representation of non-character data, and LenB reports the number of bytes needed to store the string representation of noncharacter data ... Returns a Matches collection containing information about the substrings in a larger string that match a pattern string Replace Replaces all substrings in a larger string that match a pattern string with a second string Test Indicates whether the search of a string has succeeded in finding a pattern... Description Marks the next character as either a special character (such as for the newline character) or as a literal (if that character otherwise has special meaning in a pattern search string)... The special characters are: f form feed character newline character carriage return character tab character v vertical tab character ^ Matches the beginning of input $ Matches the end of input

Ngày đăng: 26/03/2019, 17:13

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan