9951 explained code solutions for 126 technologies


python-regexHow to use word boundaries in Python Regex?


Word boundaries are used in Python Regex to match the beginning or end of a word.

import re

# Match the beginning of a word
result = re.search(r'\bcat', 'The cat in the hat')
print(result.group())

Output example

cat

Code explanation

  • \b: A word boundary which matches the beginning or end of a word
  • cat: The word to match
  • The cat in the hat: The string to search

Helpful links

Edit this code on GitHub