C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Pattern: We specify the pattern \S+ in the re.findall method. This means "one or more non-whitespace characters."
Len: We use the len() built-in to count the number of elements in the resulting list. This equals the number of words in the input string.
Python program that counts words
import re
def wordcount(value):
# Find all non-whitespace patterns.
list = re.findall("(\S+)", value)
# Return length of resulting list.
return len(list)
value = "To be or not to be, that is the question."
print(wordcount(value))
value = "Stately, plump Buck Mulligan came from the stairhead"
print(wordcount(value))
value = ""
print(wordcount(value))
Output
10
8
0
So: The example method does not count "word endings" but rather the words themselves.