在 Vim 中交换两个字符串的最简单方法是什么? [英] What is the easiest way to swap occurrences of two strings in Vim?
问题描述
将所有出现的 string_a
替换为 string_b
的最简单方法是什么,同时将任何已经是 string_b
的内容更改为 <代码>string_a?我目前的方法如下:
What is the easiest way to replace all occurrences of string_a
with string_b
while at the same time changing anything that was already string_b
into string_a
? My current method is as follows:
:s/string_a/string_c/g
:s/string_b/string_a/g
:s/string_c/string_b/g
虽然这有效,但它需要额外的输入并且似乎效率低下.有人知道更好的方法吗?
Although this works, it requires extra typing and seems inefficient. Does anybody know of a better way to do this?
推荐答案
我会这样做:
:%s/\v(foo|bar)/\={'foo':'bar','bar':'foo'}[submatch(0)]/g
但是打字太多了,所以我会这样做:
But that's too much typing, so I'd do this:
function! Mirror(dict)
for [key, value] in items(a:dict)
let a:dict[value] = key
endfor
return a:dict
endfunction
function! S(number)
return submatch(a:number)
endfunction
:%s/\v(foo|bar)/\=Mirror({'foo':'bar'})[S(0)]/g
但这仍然需要输入 foo
和 bar
两次,所以我会做这样的事情:
But that still requires typing foo
and bar
twice, so I'd do something like this:
function! SwapWords(dict, ...)
let words = keys(a:dict) + values(a:dict)
let words = map(words, 'escape(v:val, "|")')
if(a:0 == 1)
let delimiter = a:1
else
let delimiter = '/'
endif
let pattern = '\v(' . join(words, '|') . ')'
exe '%s' . delimiter . pattern . delimiter
\ . '\=' . string(Mirror(a:dict)) . '[S(0)]'
\ . delimiter . 'g'
endfunction
:call SwapWords({'foo':'bar'})
如果你的一个词包含一个/
,你必须传入一个你知道你的词都不包含的分隔符,例如
If one of your words contains a /
, you have to pass in a delimiter which you know none of your words contains, .e.g
:call SwapWords({'foo/bar':'foo/baz'}, '@')
这还有一个好处是能够一次交换多对单词.
This also has the benefit of being able to swap multiple pairs of words at once.
:call SwapWords({'foo':'bar', 'baz':'quux'})
这篇关于在 Vim 中交换两个字符串的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!