'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 1:[1]
I am all for designing under hard constraints but pragmatism has value, too. What good is it to wait for someone else to write you a super fancy one-liner when you can write three super simple commands on the spot?
:%s/word1/§§§§/g
:%s/word2/word1/g
:%s/§§§§/word2/g
If you really dig the mystique of one-liners:
:%s/word1/§§§§/g|%s/word2/word1/g|%s/§§§§/word2/g
Solution 2:[2]
I doubt this exactly what you looking for, however Tim Pope's Abolish provides the :Subvert/:S command which can make swapping easy
:%S/{foo,bar}/{bar,foo}/gw
This will swap the following:
foo -> bar
bar -> foo
:Subvert takes similar flags to :s. I am using w for word-wise and g for global
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | romainl |
| Solution 2 | Peter Rincker |
