Python Practice › RegEx Programs › Program 12
Match whole words only
Write a Python program to count the word “test” but not “testing” or “latest”.
Output
2 3
Approach
\btest\b.
Solution
import re text = "test testing latest test. Test"print(len(re.findall(r"\btest\b", text)), len(re.findall(r"\btest\b", text, re.I)))Output
2 3
Line by line
Line 4
With re.I, “Test” also counts.
Learn the concept
New to this topic? Read the lesson, then come back.