How do I search and replace only whole words and not partial matches in Vim?
Answer
:%s/\<word\>/replacement/g
Explanation
How it works
In Vim's regular expressions, \< and \> are word boundary anchors:
\<matches the beginning of a word.\>matches the end of a word.
When used in a substitute command, they ensure that only complete word matches are replaced, preventing accidental changes to substrings within larger words.
The syntax is:
:%s/\<word\>/replacement/g
This replaces every occurrence of the exact word word throughout the file, but will not touch wordy, sword, password, or any other string that merely contains word as a substring.
Example
Consider this code:
var = "hello"
variable = "world"
var_name = "test"
my_var = var
Running :%s/var/config/g without word boundaries would produce:
config = "hello"
configiable = "world"
config_name = "test"
my_config = config
The word variable was incorrectly changed to configiable. Instead, use word boundaries:
:%s/\<var\>/config/g
Result:
config = "hello"
variable = "world"
var_name = "test"
my_config = config
Only standalone occurrences of var were replaced. Note that var_name still changed because _ is not a word character in Vim's default definition, so var in var_name starts at a word boundary.
Tips
- Add the
cflag (:%s/\<var\>/config/gc) to confirm each replacement interactively. - The
*command in normal mode searches with word boundaries by default, making it easy to verify matches before substituting. - Word boundaries also work in search:
/\<var\>finds only whole-word matches ofvar.