By default, patterns match anywhere in a string. In many cases you want patterns to match in only specific parts of a string. For example, if you want to match words at start with a pattern you don't want to match characters in the middle of the word.
This can be achieved using anchors. Anchors don't match any characters, but instead they specify where in a string matches are allowed to begin and/or end.
Some common anchors are:
Anchor | Description |
---|---|
^ | Match at the start of a line |
$ | Match at the end of a line |
\< | Match at the start of a word |
\> | Match at the end of a word |
\%^ | Match at the start of a file |
\%$ | Match at the end of a file |
Lets demonstrate the behavior of some of the more common anchors using the buffer below:
First, let's perform an un-anchored search to show the default behavior:
We found 8 instances of the string "John", which appear at all different parts of the respective strings.
Next lets add the "^" anchor and search again:
This matches only the 3 locations where "John" appears at the start of the line. Compare that to search with the "$" anchor:
Here we match at the only two locations where the lines end with "John".
Now let's try anchoring to work boundaries. First, let's try anchoring to the start of the word with "\<"
Finally, lets anchor to the tail of the word, using ">":