Anchors match the start or end of the text.
^ matches the start, and
$ matches the end. Anchors are important because regex engines typically match
substrings of the text, but sometimes you want the entire text to match.
For example: Let’s say a user entered a phone number, and you want to check if it is valid. You use the following expression:
'+'? [ascii_digit '-()/ ']+
But this also finds a match in texts that aren’t valid phone numbers:
agt4578409tuirüzojhüziou54x ^^^^^^^ ^^ match 1 match 2
To make sure the entire text has to match, we can add
^ '+'? [ascii_digit '-()/ ']+ $
^ ensures the match is at the start of the text, and the
ensures that the end of the match is also the end of the search text.
Anchors can appear anywhere, to implement more complicated logic. For example:
('a' | ^) 'b'
This matches either
ab or just
b. But if there is no
a, the match must be at the start of the