Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))

Problem

You want to count the characters, words, and lines in a string.

Solution

Sample code folder: Chapter 05\RegexCountParts

Use separate regular expressions to count words, characters, and lines in a string of any length.

Discussion

The following code demonstrates three very short regular expressions that provide simple counts of characters, words, and lines in a string of any length:

Imports System.Text.RegularExpressions ' …Later, in a method… Dim quote As String = _ "The important thing" & vbNewLine & _ "is not to stop questioning." & vbNewLine & _ "--Albert Einstein" & vbNewLine Dim numBytes As Integer = quote.Length * 2 Dim numChars As Integer = Regex.Matches(quote, ".").Count Dim numWords As Integer = Regex.Matches(quote, "\w+").Count Dim numLines As Integer = Regex.Matches(quote, ".+\n*").Count MsgBox(String.Format( _ "{0}{5}bytes: {1}{5}Chars: {2}{5}Words: {3}{5}Lines: {4}", _ quote, numBytes, numChars, numWords, numLines, vbNewLine))

The number of bytes in the string is also displayed, as shown in Figure 5-50, but the string's Length property provides this count directly without having to resort to a regular expression.

Figure 5-50. Using simple regular expressions to count characters, words, or lines in a string

See Also

Recipe 5.38 also discusses the results of regular expression processing.

Категории