Nailing Things Down
Whenever you try to match a pattern, it’s going to try to match in every location until it finds a match. An anchor allows you to restrict where the pattern can match. Essentially, an anchor is something that matches a “nothing”, but a special kind of nothing that depends on its surroundings. You could also call it a rule, a constraint, or an assertion. Whatever you care to call it, it tries to match something of zero width and either succeeds or fails. (Failure merely means that the pattern can’t match that particular way. The pattern will go on trying to match some other way, if there are any other ways left to try.)
The special symbol \b matches
at a word boundary, which is defined as the “nothing” between a word
character (\w) and a nonword
character (\W), in either order. (The
characters that don’t exist off the beginning and end of your string are
considered to be nonword characters.) For example:
/\bFred\b/
would match “Fred” in both
“The Great Fred” and “Fred the Great”, but not in “Frederick the Great” because the “d” in “Frederick” is not followed by a nonword
character.
In a similar vein, there are also anchors for the beginning and
the end of the string. If it is the first character of a pattern, the
caret (^) matches the “nothing” at
the beginning of the string. Therefore, the pattern /^Fred/ would match “Fred” in “Frederick the Great” but not in “The
Great Fred”, whereas /Fred^/ wouldn’t match either. (In fact, it doesn’t even make much sense.) The ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access