Menu
Coddy logo textTech

Boundaries

Lesson 13 of 28 in Coddy's RegEx in Python course.

Word boundaries are used to match positions where a word starts or ends. The two main word boundary markers are \b and \B.

  • <strong>\b</strong>: Matches a word boundary, the position where a word starts or ends.
  • <strong>\B</strong>: Matches a non-word boundary, the position where there isn't a word boundary.
import re

text = "cat scatter cater"
pattern = r"\bcat\b"

matches = re.findall(pattern, text)

print(matches)  # Output: ['cat']

In the above example, the pattern \bcat\b matches the word "cat" only when it appears as a whole word, thanks to the word boundary markers \b on either side.

challenge icon

Challenge

Easy

Write a function named find_whole_words that takes a text string and a word as input, and returns a list of all occurrences of the whole word in the text.

Try it yourself

import re

def find_whole_words(text, word):
    # Write code here

All lessons in RegEx in Python