Count Number of Words using Regex in VB.NET

Today in VB.NET, we will create again a program that counts the number of words in VB.NET. But here, we will now use Regex. I already made a tutorial about how to create this program but i used Split method with (CChar(" ")) that time. See here: Word Count Program in VB.NET Now, let's start this tutorial! 1. Let's start with creating a Windows Form Application for this tutorial by following the following steps in Microsoft Visual Studio: Go to File, click New Project, and choose Windows Application. 2. Next, add one TextBox named TextBox1 and a Button named Button1 labeled as "Count Number of Words". You must design your interface like this: design 3. Import System.Text.RegularExpressions because we will use Regex syntax here.
  1. Imports System.Text.RegularExpressions
4. Now put add this code for your code module. This code is for Button1_Click. This will trigger to count the number of words in your TextBox. Initialize variable txt as string that will hold the inputted value of our textbox1.
  1. Dim txt As String = TextBox1.Text
Instantiate a Regex variable named parser that has \w+. A / as an escaped character indicates to match with a character, w means to match any word character, and + here indicates to match the previous element more times.
  1. Dim parser As New Regex("\w+")
Declare variable totalMatches As Integer that will match the parser variable using Matches and count method in regex.
  1. Dim totalMatches As Integer = parser.Matches(txt).Count
Display the number of words and put toString method to make the totalMatches as string.
  1.         MessageBox.Show("Number of words: " & _
  2.            totalMatches.ToString)
Full source code:
  1. Imports System.Text.RegularExpressions
  2.  
  3. Public Class Form1
  4.  
  5.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  6.         Dim txt As String = TextBox1.Text
  7.         Dim parser As New Regex("\w+")
  8.         Dim totalMatches As Integer = parser.Matches(txt).Count
  9.  
  10.         MessageBox.Show("Number of words: " & _
  11.            totalMatches.ToString)
  12.     End Sub
  13. End Class
Output: output Best Regards, Engr. Lyndon Bermoy IT Instructor/System Developer/Android Developer/Freelance Programmer If you have some queries, feel free to contact the number or e-mail below. Mobile: 09488225971 Landline: 826-9296 E-mail:[email protected] Add and Follow me on Facebook: https://www.facebook.com/donzzsky Visit and like my page on Facebook at: https://www.facebook.com/BermzISware

Add new comment