how can I substitute a single word via regular expression?

:s/\(\s\+\)word\(\s\+\)/\1new_word\2/g

Alternatively, rather than saving your whitespace and then restoring it, you can use

        :s/\<word1\>/new_word/g

This respects the "word" boundaries in vim, as defined by the 'iskeyword' setting. Andrea's requires that the boundary be whitespace. Mine requires that the boundaries around a word are non-"word" characters. Both are valid solutions, depending on what you consider your word. Consider the example (with the period):

        Your dog and my dog's dogged fleas are on his dog.

:s/\<dog\>/cat/g

        Your cat and my cat's dogged fleas are on his cat.

Andrea's ":s/\(\s\+\)dog\(\s\+\)/\1cat\2/g" becomes

        Your cat and my dog's dogged fleas are on his dog.

Both are perfectly valid regexps, that do exactly what they describe. Depending on which you want/need, choose accordingly. :)

-tim



Reply via email to