Anchors in Neovim Patterns

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:

Initial Conditions
John·Evans·Kim
Aaron·Mia·Johnson
Johnny·Matthew·Martin
Nancy·Kathleen·John
Heather·Vanessa·Perez-Johnson
Scott·Johnathon·Ford
Johnnie·Dillon·Odom
Jessica·Jennifer·LittleJohn
COMMAND
Top
1:1
/John

First, let's perform an un-anchored search to show the default behavior:

Search for John
John·Evans·Kim
Aaron·Mia·Johnson
Johnny·Matthew·Martin
Nancy·Kathleen·John
Heather·Vanessa·Perez-Johnson
Scott·Johnathon·Ford
Johnnie·Dillon·Odom
Jessica·Jennifer·LittleJohn
NORMAL
22%
2:11
 

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:

Anchored search for John
John·Evans·Kim
Aaron·Mia·Johnson
Johnny·Matthew·Martin
Nancy·Kathleen·John
Heather·Vanessa·Perez-Johnson
Scott·Johnathon·Ford
Johnnie·Dillon·Odom
Jessica·Jennifer·LittleJohn
NORMAL
33%
3:1
 

This matches only the 3 locations where "John" appears at the start of the line. Compare that to search with the "$" anchor:

Anchored search for John
John·Evans·Kim
Aaron·Mia·Johnson
Johnny·Matthew·Martin
Nancy·Kathleen·John
Heather·Vanessa·Perez-Johnson
Scott·Johnathon·Ford
Johnnie·Dillon·Odom
Jessica·Jennifer·LittleJohn
NORMAL
44%
4:16
 

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 "\<"

Anchored search for John
John·Evans·Kim 
Aaron·Mia·Johnson
Johnny·Matthew·Martin
Nancy·Kathleen·John
Heather·Vanessa·Perez-Johnson
Scott·Johnathon·Ford
Johnnie·Dillon·Odom
Jessica·Jennifer·LittleJohn
NORMAL
22%
2:11
 

Finally, lets anchor to the tail of the word, using ">":

Anchored search for John
John·Evans·Kim
Aaron·Mia·Johnson
Johnny·Matthew·Martin
Nancy·Kathleen·John
Heather·Vanessa·Perez-Johnson
Scott·Johnathon·Ford
Johnnie·Dillon·Odom
Jessica·Jennifer·LittleJohn
NORMAL
44%
4:16