Anchors

Anchors don’t match any characters; they match places within a string. The two most common anchors are ^ and $, which match the beginning and end of a line, respectively. The following table lists the anchoring patterns used to match certain boundaries in regular expressions:

Assertion

Meaning

^

Matches at the beginning of the string (or line, if /m is used)

$

Matches at the end of the string (or line, if /m is used)

\b

Matches at word boundary (between \w and \W)

\B

Matches except at word boundary

\A

Matches at the beginning of the string

\Z

Matches at the end of the string or before a newline

\z

Matches only at the end of the string

\G

Matches where previous m//g left off

\c

Suppresses resetting of search position when used with \g. Without \c, search pattern is reset to the beginning of the string.

The $ and \Z assertions can match not only at the end of the string, but also one character earlier than that, if the last character of the string is a newline.

Get Perl in a Nutshell, 2nd 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.