ÄúµÄλÖãºÑ°ÃÎÍøÊ×Ò³£¾±à³ÌÀÖÔ°£¾VBScript£¾VBScript


objects constants operators statements functions properties methods







OBJECT:  Matches Collection

Matches Collection

The Matches Collection is a collection of objects that contains the results of a search and match operation that uses a regular expression.

Simply put, a regular expression is a string pattern that you can compare against all or a portion of another string. However, in all fairness, be warned that regular expressions can get very complicated.

The RegExp object can be used to search for and match string patterns in another string. A Match object is created each time the RegExp object finds a match. Since, zero or more matches could be made, the RegEXp object actually return a collection of Match objects which is refered to as a Matches collection.

The following code is a simplier, working version of a program published by Microsoft. Note how the For Each ... Next statement is used to loop through the Matches collection.

Code:
<%
'this sub finds the matches
Sub RegExpTest(strMatchPattern, strPhrase)
    'create variables
    Dim objRegEx, Match, Matches, StrReturnStr
    'create instance of RegExp object
    Set objRegEx = New RegExp

    'find all matches
    objRegEx.Global = True
    'set case insensitive
    objRegEx.IgnoreCase = True
    'set the pattern
    objRegEx.Pattern = strMatchPattern

    'create the collection of matches
    Set Matches = objRegEx.Execute(strPhrase)

    'print out all matches
    For Each Match in Matches
        strReturnStr = "Match found at position "
        strReturnStr = strReturnStr & Match.FirstIndex & ". Match Value is '"
        strReturnStr = strReturnStr & Match.value & "'." & "<BR>" & vbCrLf
        'print
        Response.Write(strReturnStr)
  :  Next
End Sub

'call the subroutine
RegExpTest "is.", "Is1 is2 Is3 is4"
%>

Output:
Match found at position 0. Match Value is 'Is1'.
Match found at position 4. Match Value is 'is2'.
Match found at position 8. Match Value is 'Is3'.
Match found at position 12. Match Value is 'is4'.