You want a quick count of the number of matches a regular expression finds in a string.
Sample code folder: Chapter 05\RegexCountMatch
Use the Count property of the Matches() method of the Regex object.
The following example code shows how to use regular expressions to count words in a string, as defined by the pattern \w+:
Imports System.Text.RegularExpressions ' …Later, in a method… Dim quote As String = "The important thing is not to " & _ "stop questioning. --Albert Einstein" Dim parser As New Regex("\w+") Dim totalMatches As Integer = parser.Matches(quote).Count MsgBox(quote & vbNewLine & "Number words: " & _ totalMatches.ToString)
This example returns a count of the number of matches, not a collection of matches. Figure 5-43 shows the results as displayed by the message box.
Figure 5-43. Using the Regex object to count words in a string
This technique can be useful for many other types of regular expression searches, too. For example, the regular expression shown in Recipe 5.37 can be used to quickly determine the number of numbers of all types in a string of any size.
Recipes 5.13 and 5.37 discuss regular expression processing in additional detail.