Recipe 5.38. Getting a Count of Regular Expression Matches


Problem

You want a quick count of the number of matches a regular expression finds in a string.

Solution

Sample code folder: Chapter 05\RegexCountMatch

Use the Count property of the Matches() method of the Regex object.

Discussion

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.

See Also

Recipes 5.13 and 5.37 discuss regular expression processing in additional detail.




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net