Count Number of Words Using Regex in VB.NET

Count Number of Words Using Regex in VB.NET

Problem

Create a Windows Form Application program in Visual Basic.Net that will allow users to count the number of words using VB.NET.

Description

This tutorial will allow the user to use a label to count the number of words in a text box.

Before the tutorial the following are required to start:

  • Microsoft Visual Studio 2008 – Above

The tutorial starts here:

  1. Open Microsoft Visual Studio 2012
  2. Select a New Project on the File menu.
  3. Select Visual Basic, Windows Form Application then click OK.
  4. We need to design our form by the following controls:
  • 2 Label – 1 label for the counter’s label and 1 label for the counter itself.
  • 1 Text box – text box for the Text.
  1. We will also name our form controls in this way:
  • txttext is the name of the textbox for the Search text box.
  • lblcount is the name of the button for the search button.
  1. This is how we design the form. (Feel free to layout your own)
Count Number of Words Using Regex in VB.NET - Form Design
Count Number of Words Using Regex in VB.NET – Form Design

Figure 1. Design of the Form

  1. Paste the following codes to add a function.

Code here

Function wordCount(ByVal str As String)
        Dim NumberOfWord As Integer
        NumberOfWord = UBound(Split(Trim(Replace(str, Space(2), Space(1))))) + 1
        Return NumberOfWord
End Function

End Code

Code Explanation:

These codes will recognize the word once it is separated by a space/split from a string.

  1. Double click the text box and paste the following code.

Code here

If txttext.Text = "" Then
            lblcount.Text = "Count Words: " & 0
Else
            lblcount.Text = "Count Words: " & wordCount(txttext.Text)
End If

End Code

Count Number of Words Using Regex in VB.NET - Final Output
Count Number of Words Using Regex in VB.NET – Final Output

Code Explanation:

The code counts the number of words from the text box and displays it in the label named lblcount. If the text box doesn’t have any text it will return a “0” count.­

Summary

We have created a sample program in VB.NET language using the Regex type that counts the number of words. Please follow the steps in order for you to run and execute the project properly.

The project and source code is available for download and you may modify it based on your preferences and requirements.

Author:

Name: Charlie Devera
Email Address: charliedevera000@gmail.com

Free Download Source code (Count Number of Words Using Regex in VB.NET)

You may visit our facebook page for more information, inquiries and comments.

Hire our team to do the project.

­

­­­

, , ,

Post navigation