2

I have been going through some answers to a vimgolf, and stumbled upon this regex:

:s/\_W*/-/g|x<CR>

Which converts

abcdefghijklm

to

-a-b-c-d-e-f-g-h-i-j-k-l-m-

The regex (without unrelated keystrokes) is /\_W*/-/. The manual indicates that: \W stands for non-word character: [^0-9A-Za-z_]

\_x Where "x" is any of the characters above: The character class with end-of-line added

So \_W is non-word characters with end-of-line added.

How does that put the dashes between the characters? Is there a hidden metacharacter between each character in vim text?

3

This is not a question of hidden character, the trick comes from the * combined with the flag g:

Specifying * after a character classe will match "zero or more" items (which includes an empty string): between a and b there is zero non-word character, thus \W* will match this "not existing space".

For example you could also have used \_s* or \_d* and still get the same result since you match zero items of the class.

0

To add to what statox mentioned above, if you want to avoid matching against the "not existing" space, use \+ instead of * to match one or more instances of the non-word character:

:s/\_W\+/-/g

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.