How do I search and replace only whole word matches, not partial matches?
Answer
:%s/\<old\>/new/g
Explanation
Wrapping your search pattern in \< and \> word boundary anchors ensures that Vim only matches the exact whole word, preventing accidental replacements inside longer words. Without these anchors, replacing or would also change world to wnewd.
How it works
\<matches the beginning of a word boundary\>matches the end of a word boundary- Together they ensure the pattern only matches when it appears as a standalone word, surrounded by non-word characters or at the start/end of a line
Example
Given the text:
int i = 0;
int index = i;
print(i);
Running :%s/i/counter/g (without boundaries) would produce a mess:
countert counter = 0;
countert counterndex = counter;
prcountert(counter);
Running :%s/\<i\>/counter/g (with boundaries) correctly yields:
int counter = 0;
int index = counter;
print(counter);
Only the standalone i was replaced, leaving int, index, and print untouched.
Tips
- Use
*on a word first to set the search register with boundaries automatically, then:%s//new/greuses that bounded pattern - Combine with the
cflag for interactive confirmation::%s/\<old\>/new/gc - In very magic mode (
\v), word boundaries are<and>without extra backslashes::%s/\v<old>/new/g - You can use boundaries on just one side:
\<prematches words starting withpre,end\>matches words ending withend - This is equivalent to
\bword\bin Perl-style regex, but Vim uses\<and\>instead