6.2.6 The Anchor Characters
Sometimes, we want to apply the regular expression from a defined point.
In other words, we want to anchor the regular expression so it is not
permitted to match anywhere in the string, just from a certain point.
The anchor operators allow us to do this. When we start a regular
expression with a ^
, it anchors the regular expression to the
beginning of the string. This means that whatever the regular
expression starts with must be matched at the beginning of the
string. For example, ^aa*
will not match strings that contain
one or more a
's; rather it matches strings that start with
one or more a
's.
We can also use the $
at the end of the string to anchor the
regular expression at the end of the string. If we applied this to our
last regular expression, we have ^aa*$
which now matches
only those strings that consist of one or more a
's. This
makes it clear that the regular expression cannot just look anywhere in
the string, rather the regular expression must be able to match the
entire string exactly, or it will not match at all.
In most cases, you will want to either anchor a regular expression to
the start of the string, the end of the string, or both. Using a
regular expression without some sort of anchor can also produce
confusing and strange results. However, it is occasionally useful.