liveBook · Manning

Lookbehind assertion

As explained in The Well-Grounded Rubyist, Fourth Edition

A lookbehind assertion is a regular-expression assertion that checks text immediately preceding the current match position without consuming that text.

A lookbehind assertion constrains a match by checking the text immediately before the current position. It is zero-width: the preceding text must satisfy the assertion, but it is neither matched nor consumed. section 11.5.3

Require or reject preceding text

Use /(?<=David )BLACK/ to match BLACK only when it follows “David ”. Use /(?<!David )BLACK/ for the opposite condition: match BLACK only when it does not follow “David”.

Distinguish lookbehind from nearby regular-expression constructs:

  • Lookahead assertions inspect following text without consuming it; lookbehind assertions perform the equivalent check on preceding text. section 11.5.3
  • Non-capturing groups consume matched characters but omit them from numbered captures; lookbehind assertions consume nothing. section 11.5.3

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains positive and negative syntax plus zero-width behavior, without detailing engine implementation.
Examples
Uses BLACK preceded or not preceded by “David ” as the concrete matching example.
What it assumes
Assumes familiarity with regular-expression matching and introduces lookbehind alongside lookahead and grouping behavior.
What you can do after
Apply lookbehind assertions in Ruby regular expressions to impose preceding-text conditions without consuming that text.
How it connects
Relates lookbehind assertions to lookahead assertions, zero-width assertions, captures, and non-capturing groups.

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.