liveBook · Manning

Word boundary

As explained in Regular Expression Puzzles and AI Coding Assistants

A word boundary is a regular-expression zero-width assertion that matches a position at the transition between word and non-word characters or at a string edge.

A pattern can look perfect and still catch the wrong thing. Searching for lowercase words that start with x and end with y needs more than x[a-z]*y: that pattern can accept a prefix such as xyxy from xyxyblah. The missing ingredient is a check on where the word begins and ends. section 2.2

In Python and many regular-expression engines, \b is an explicit zero-width word-boundary assertion. Put it around the word-shaped portion: \bx[a-z]*y\b. It brackets the intended match without becoming part of the returned word. section 2.5

Boundary markers solve one problem, not every definition-of-word problem:

  • Use [a-z] when lowercase letters are the requirement; \w also admits digits and underscores. section 2.3 section 2.6
  • Do not assume a greedy letter pattern supplies boundaries. It can avoid some prefixes yet still accept an embedded fragment. section 2.2
  • Build the same bracketing logic with lookbehind and lookahead only when needed; fixed-width lookbehind and line edges make that version more intricate. section 2.5
  • Treat AI-generated regexes as drafts. A pattern may use \b correctly while still choose an overly broad character class or irrelevant flags. section 2.6

The x-to-y filter

For text containing xenomorphically, xylology, and xerochasy, \bx[a-z]*y\b returns those complete lowercase words. The boundary checks keep a longer surrounding token from donating a misleading prefix or suffix. section 2.5

>>> pat4 = re.compile(r'\bx[a-z]*y\b')
>>> re.findall(pat4, txt)
['xenomorphically', 'xylology', 'xerochasy']

Inspect the compact boundary pattern and its complete-word results before trusting a more elaborate alternative. section 2.5

How Regular Expression Puzzles and AI Coding Assistants covers it

How deep it goes
Explains \b through a worked pattern and contrasts it with a more intricate lookaround construction.
Examples
Tests x-to-y matching against word lists, xyxyblah, and patterns generated by coding assistants.
What it assumes
Assumes familiarity with regular-expression patterns while introducing \b as an explicit zero-width match.
What you can do after
Apply it via Python re patterns to select whole words while checking whether the chosen character class matches the intended word definition.
How it connects
Connects word boundaries to quantifiers, character classes, lookahead, lookbehind, and regular-expression matching.

Also explained in

Compare how 3 books explain word boundary →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Regular Expression Puzzles and AI Coding Assistants. The section links point to the parts of the book it draws on.