Python Practice › RegEx Programs › Program 12

Match whole words only

EasyRegEx Programs · 12 of 20

Write a Python program to count the word “test” but not “testing” or “latest”.

Advertisement
Output
2 3

Approach

  1. \btest\b.

Solution

Python
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.

More regex programs

← All 20 RegEx Programs

Leave a Comment