3.4. Using Anchors

An anchor is a special expression that matches a position in a string rather than a character or sequence of characters. As we’ll see later, this is a simple case of a zero-width assertion, a match that doesn’t consume any of the string when it matches.

The most common anchors were already listed at the beginning of this chapter. The simplest are ^ and $, which match the beginning and end of the string.

string  = "abcXdefXghi"
/def/  =~ string     # 4
/abc/  =~ string     # 0
/ghi/  =~ string     # 8
/^def/ =~ string     # nil
/def$/ =~ string     # nil
/^abc/ =~ string     # 0
/ghi$/ =~ string     # 8

However, I’ve told a small lie. These anchors don’t actually match the beginning and end of the string but of the line. Consider the same patterns applied ...

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.