'^' and dollar
'$' characters have special meaning in a regexp. They are called “anchors”.
^ matches at the beginning of the text, and the dollar
$ – in the end.
For instance, let’s test if the text starts with
^Mary means: “the string start and then Mary”.
Now let’s test whether the text ends with an email.
To match an email, we can use a regexp
To test whether the string ends with the email, let’s add
$ to the pattern:
We can use both anchors together to check whether the string exactly follows the pattern. That’s often used for validation.
For instance we want to check that
str is exactly a color in the form
# plus 6 hex digits. The pattern for the color is
To check that the whole string exactly matches it, we add
The regexp engine looks for the text start, then the color, and then immediately the text end. Just what we need.
Anchors just like
\b are tests. They have zero-width.
In other words, they do not match a character, but rather force the regexp engine to check the condition (text start/end).
The behavior of anchors changes if there’s a flag
m (multiline mode). We’ll explore it in the next chapter.