advertisement
Login | Register   
  Include Code  Search Tips
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   TIP BANK
Browse DevX
Partners & Affiliates
advertisement
advertisement
Tip of the Day
Tip formerly from VB2TheMax
Expertise: Intermediate
Language: VB5,VB6,VBS
July 7, 2001
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 library
Function 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 \b sequences)
re.Pattern = "\b\w+\b"
' 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).Count
End Function

It's quick, easy and you get access to all the articles on DevX.
This registration/login is to allow you to read articles on devx.com.
Already a member?





Francesco Balena
If you have a hot tip and we publish it, we'll pay you. However, due to accounting overhead we no longer pay $10 for a single tip submission. You must accumulate 10 acceptable tips to receive payment. Be sure to include a clear explanation of what the technique does and why it's useful. If it includes code, limit it to 20 lines if possible. Submit your tip here.
advertisement
advertisement