Search code examples
pythonregexvim

Reverse a word in Vim


How can I reverse a word in Vim? Preferably with a regex or normal-mode commands, but other methods are welcome too:

word => drow

Thanks for your help! PS: I'm in windows XP

Python is built in supported in my vim, but not Perl.


Solution

  • Here is another (pythonic) solution based on how this works:

    :echo join(reverse(split('hello', '.\zs')), '')
    olleh
    

    If you want to replace all words in the buffer,

    :%s/\(\<.\{-}\>\)/\=join(reverse(split(submatch(1), '.\zs')), '')/g
    

    This works by first creating a list of characters in the word, which is reversed and joined back to form the word. The substitute command finds each word and then passes the word to the expressions and uses the result as replacement.