Find regular expression matches in a string

Started by nandagopal, Nov 07, 2008, 06:47 PM

Previous topic - Next topic

nandagopal

Before using regular expressions, select the Project menu's References command and select the Microsoft VBScript Regular Expressions 1.0" library.

When the user clicks the Go button, the program makes a RegExp object. It sets the object's Pattern, IgnoreCase, and Global properties.

It then calls thue object's Execute method. This method returns a collection of Match objects describing the pattern matches. If the Global property is False, it only returns the first Match. The program loops through the Matches, using their data to highlight the matched text in the RichTextBox.


Private Sub cmdGo_Click()
Dim matches As MatchCollection
Dim a_match As Match

    On Error Resume Next

    Dim reg_exp As New RegExp
    reg_exp.Pattern = txtPattern.Text
    reg_exp.IgnoreCase = True
    reg_exp.Global = True

    ' Copy the text to the result RichTextBox.
    rchResult.Text = txtString.Text

    ' Color the matched text.
    Set matches = reg_exp.Execute(txtString.Text)
    For Each a_match In matches
        rchResult.SelStart = a_match.FirstIndex
        rchResult.SelLength = a_match.Length
        rchResult.SelColor = vbRed
    Next a_match

    rchResult.SelStart = 0
    rchResult.SelLength = 0
End Sub