liveBook · Manning

Lookahead

As explained in The Well-Grounded Rubyist, Fourth Edition

A lookahead assertion checks whether a specified subexpression follows the current position without consuming the checked characters.

A lookahead assertion tests what follows the current position without consuming those characters. A positive lookahead uses (?=...), while a negative lookahead uses (?!...). section 11.5.3

Match numbers followed by a period

Given str = "123 456. 789", the pattern /\d+(?=\.)/ matches 456. The period satisfies the assertion but remains outside the match, so it can still be matched by later pattern components. section 11.5.3

Keep these mechanics in mind:

  • Treat the assertion as zero-width: checking the next characters does not advance the match position. section 11.5.3
  • Do not expect the lookahead parentheses to create a capture; the asserted text does not populate $1. section 11.5.3
  • Contrast lookahead with lookbehind, which checks preceding text instead of following text. section 11.5.3
str = "123 456. 789"
m = /\d+(?=\.)/.match(str)

Run the compact Ruby example to inspect which number sequence matches while the period remains unconsumed. section 11.5.3

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains positive and negative syntax, zero-width behavior, consumption, and captures through a numeric example.
Examples
Uses /\d+(?=\.)/ against "123 456. 789" to demonstrate a nonconsuming period check.
What it assumes
Assumes familiarity with regular expression matching, anchors, assertions, and capture groups.
What you can do after
Apply it via Ruby regexp syntax to require following text while leaving that text outside the match.
How it connects
Connects regular expression assertions with anchors, lookbehind assertions, matching, and capture 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.