Anchors, or atomic zero-width assertions, cause a match to succeed or fail depending on the current position in the string, but they do not cause the engine to advance through the string or consume characters. The meta-characters listed in Table 1 are anchors.
Assertion |
Description |
^ |
The match must start at the beginning of the string or line. |
$ |
The match must occur at the end of the string or before \n at the end of the line or string. |
\A |
The match must occur at the start of the string. |
\Z |
The match must occur at the end of the string or before \n at the end of the string. |
\z |
The match must occur at the end of the string. |
\G |
The match must occur at the point where the previous match ended. |
\b |
The match must occur on a boundary between a \w (alphanumeric) and a \W (non-alphanumeric) character. |
\B |
The match must not occur on a \b boundary. |
Table 1: Anchors
Pattern |
Matches |
^\d{3} |
"901" in "901-333-" |
-\d{3}$ |
"-333" in "-901-333" |
\A\d{3} |
"901" in "901-333-" |
-\d{3}\Z |
"-333" in "-901-333" |
-\d{3}\z |
"-333" in "-901-333" |
\G\(\d\) |
"(1)", "(3)", "(5)" in "(1)(3)(5)[7](9)" |
\b\w+\s\w+\b |
"them theme", "them them" in "them theme them them" |
\Bend\w*\b |
"ends", "ender" in "end sends endure lender" |
Table 2: Examples for the usage of anchors