advertisement
Premier Club Log In/Registration
  Include Code  Search Tips
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   SKILLBUILDING  |   TIP BANK  |   SOURCEBANK  |   FORUMS  |   NEWSLETTERS
Browse DevX
Partners & Affiliates
advertisement
advertisement
Tip of the Day
Average Rating: 1.3/5 | Rate this item | 3 users have rated this item.
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
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.
Please rate this item (5=best)
 1  2  3  4  5
advertisement
advertisement
Advertising Info  |   Member Services  |   Permissions  |   Help  |   Site Map  |   Network Map  |   About


The Network for Technology Professionals

Search:

About Internet.com

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers