Python: Count words in a string using Regular Expression

Last updated on November 3, 2020 Guest Contributor Loading... Post a comment

The Python program below counts the number of words in a given string. Whitespace and any special symbols except the underscore will be ignored.

import re

s = 'Lorem ipsum dolor sit amet, a f @! <> d consectetur adipiscing elit.'

pattern = re.compile(r'\w+')
matches = pattern.findall(s) 
print(len(matches))

Output:

11

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles