Find and replace whole words in vim

RegexVimEditorReplace

Regex Problem Overview


To find and replace all instances of a word in vim, I use

%s/word/newword/g

How do I change this so that it only finds instances of "word" that are whole words?

Regex Solutions


Solution 1 - Regex

You can use \< to match the beginning of a word and \> to match the end:

%s/\<word\>/newword/g

Solution 2 - Regex

For case-sensitive replace.. you can use "\C"

:%s/\<word\>\C/newword/g

It replaces only "word" with newword leaving others like Word,WORD... unreplaced.

Solution 3 - Regex

For PCRE compatible search and replace, you can use the perldo or rubydo commands as described here: http://vim.wikia.com/wiki/Perl_compatible_regular_expressions

For example:

:perldo s/\bword\b/newword/g

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionneuromancerView Question on Stackoverflow
Solution 1 - RegexsthView Answer on Stackoverflow
Solution 2 - RegexNaga KiranView Answer on Stackoverflow
Solution 3 - Regexuser3751385View Answer on Stackoverflow