Search code examples
regexvimvi

Swapping words with pure Regex


I'd like to swap two words using capture groups in Vim using only one line of regex, but I cannot find a solution to this for example

word1
word2

expecting:
word2
word1

get:
word1
word2

I've also tried s/(word1)(word2)/\2\1/g but they don't swap their position or even replace

Is there any way I can achieve this?


Solution

  • You are not matching the newline in between, and the newline is also not present in the replacement.

    For the capture groups you can escape the parenthesis:

    \(word1\)\n\(word2\)/\2\r\1/
    

    Output

    word2
    word1
    

    If you want to replace all occurrences and not have to escape the parenthesis you can use the very magic mode using \v and use %s

    %s/\v(word1)\n(word2)/\2\r\1/g
    

    If the word can be spread, you can match any character non greedy in between and also use a capture group for that in the replacement.

    %s/\v(word1)(\_.{-})(word2)/\3\2\1/g
    

    See this page for extensive documentation.