Python: Count words in a string using Regular Expression

Last updated on November 10, 2022 Guest Contributor Loading... Post a comment

The Python program below counts the number of words in a given string by using a regular expression. 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

That’s it. Further reading:

You can also check out our Machine Learning category page or Python category page for more tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles