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


