liveBook · Manning

Word boundary

As explained in The Well-Grounded Rubyist, Fourth Edition

A word boundary anchor constrains a match to a transition between word and non-word characters or to a string boundary.

A word boundary anchor, written \b, matches a position where a word character and a non-word character meet, or where the string begins or ends. It checks the position without consuming a character. For example, /\bword/ matches “word” in “!word!sword” because the exclamation mark begins a boundary, while /\Bword/ matches “word” inside “sword” because that position is not a boundary. section 11.5.3

Use the two related anchors to control whether a match may cross a word boundary:

  • \b requires a transition between a \w character and a non-\w character, or a string edge. section 11.5.3
  • Whitespace and other non-\w characters count as boundaries, so the anchor can distinguish a standalone word from the same letters inside a larger word. section 11.5.3

Match a word at its start

The pattern /\bword/ matches the first “word” in “!word!sword” but not the occurrence inside “sword”.

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains transitions, string edges, and the \b/\B contrast through a compact matching example.
Examples
Uses /\bword/ and /\Bword/ against “!word!sword” to contrast boundary and non-boundary matches.
What it assumes
Assumes basic regular-expression familiarity while defining anchors, word characters, non-word characters, and transitions.
What you can do after
Apply Ruby regular-expression anchors to distinguish standalone words from occurrences embedded in larger words.
How it connects
Connects word boundaries with regular expressions, anchors, assertions, word characters, and non-word characters.

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 The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.