liveBook · Manning

Regular-expression anchor

As explained in The Well-Grounded Rubyist, Fourth Edition

A regular-expression anchor is a zero-width pattern assertion that constrains a match to a structural position such as the start or end of text.

A regular-expression anchor is a zero-width assertion: it consumes no characters, but requires the match to occur at a structural position in the string. Anchors complement character matching by constraining where matching may proceed. section 11.5.3 section 11.5

Filtering comment lines

The regexp /^\s*#/ matches a line beginning with optional whitespace followed by #. It matches " # Pure comment!" but not " x = 1 # Code plus comment!", because the latter comment does not begin the line. section 11.5.3

Common Ruby anchors express these positions and boundary conditions:

  • \Z asserts the end of the string while allowing an optional trailing newline. section 11.5.3

Anchors differ from lookahead and lookbehind assertions in purpose: anchors constrain structural positions, while assertions generally require surrounding matching conditions without consuming characters. Together with quantifiers and modifiers, they refine regexp behavior. section 11.5 section 11.5.3

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains zero-width mechanics, major anchor forms, boundary differences, and a comment-filtering example without covering regexp-engine internals.
Examples
Uses comment-line filtering, line and string boundary patterns, and word-boundary matches such as /\bword/ and /\Bword/.
What it assumes
Assumes basic regular-expression matching and introduces anchors alongside quantifiers and modifiers.
What you can do after
Apply anchors in Ruby regular expressions to require matches at selected line, string, or word-boundary positions.
How it connects
Connects anchors with regular expressions, assertions, quantifiers, modifiers, character classes, and MatchData.

Also explained in

Compare how 3 books explain regular-expression anchor →

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.