Anchors
By default, if a pattern doesn’t match at the start of the string, it can “float” on down the string, trying to match somewhere else. But there are a number of anchors that may be used to hold the pattern at a particular point in a string.
The caret[*] anchor (^) marks the
beginning of the string, while the dollar sign ($) marks
the end.[†] So the pattern /^fred/
will match fred only at the start of
the string; it wouldn’t match manfred
mann. And /rock$/ will
match rock only at the end of the
string; it wouldn’t match knute
rockne.
Sometimes you’ll want to use both of these anchors to ensure that
the pattern matches an entire string. A common example is /^\s*$/, which matches a blank line. But this “blank” line may include some
whitespace characters, like tabs and spaces, which are invisible to you
and me. Any line that matches that pattern looks just like any other one
on paper, so this pattern treats all blank lines as equivalent. Without
the anchors, it would match nonblank lines as well.
Word Anchors
Anchors aren’t just at the ends of the string. The word-boundary
anchor, \b, matches at either end
of a word.[‡] So you can use /\bfred\b/ to match the word fred but not frederick or alfred or manfred
mann. This is similar to the feature often called something
like “match whole words only” in a word processor’s search
command.
Alas, these aren’t words as you and I are likely to think of
them; they’re those \w-type words made up of ordinary letters, digits, and underscores. The ...