devxlogo

Count number of words with the RegExp object

Count number of words with the RegExp object

A Visual Basic function that counts the number of words in a sentence or text file can become quickly very complex, and usually doesn’t execute fast enough for most purposes. Thanks to the RegEx object that comes with the Microsoft VBScript Regular Expression type library, this task becomes trivial. Here’s all the code that you need:

' Count the number of words in the string argument'' NOTE: requires a reference to the '       Microsoft VBScript Regular Expression type libraryFunction CountWords(ByVal Text As String) As Long    Dim re As New RegExp    ' the following pattern means that we're looking for a word character (w)    ' repeated one or more times (the + suffix), and that occurs on a word    ' boundary (leading and trailing  sequences)    re.Pattern = "w+"    ' search for *all* occurrences    re.Global = True    ' the Execute method does the search and returns a MatchCollection object    ' which in turn exposes the Count property,    '  i.e. the result we're interested into    CountWords = re.Execute(Text).CountEnd Function

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist