ProblemYou want a quick count of the number of matches a regular expression finds in a string. SolutionSample code folder: Chapter 05\RegexCountMatch Use the Count property of the Matches() method of the Regex object. DiscussionThe 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 stringThis 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. See AlsoRecipes 5.13 and 5.37 discuss regular expression processing in additional detail. |