Take the 2-minute tour ×

I have some part of a line visually selected. I would like to remove all non-word characters in the selection and replace all whitespace characters with underscores.

How would I go on about this?

share|improve this question

1 Answer 1

up vote 2 down vote accepted

The following assumes a basic familiarity with the Vim :substitute command. First replace the whitespace characters with underscores.


Typing : while text is visually selected will automatically fill in


The \%V before and after the space cause the enclosed pattern (the space) to match only within a visually-selected region. Next remove the non-word characters. Type gv to re-select the region. Then type


where \W is a Vim regex atom meaning "non-word character." See

:help /\%V
:help /\s
:help /\W
:help gv

Typing the \%V can be awkward. The vis.vim plugin simplifies this by allowing one to execute any ex command on a visually-selected region by typing : then B then the ex command, simplifying the above to

:'<,'>B s/\s/_/g
:'<,'>B s/\W//g

where again, Vim fills in the '<,'> part for you.

I replaced "space" with "whitespace characters" above after re-reading the question.

share|improve this answer
Great! I didn't know about \%V. –  Nickolay Kolev May 20 '11 at 20:19

Your Answer


