標籤:vim dictionary
Swap Two or More Words
如下檔案
Suppose that we want to swap the order of the words “dog” and “man. ”
假設我們打算把文中的dog和man兩個詞語互換,應該怎麼做呢?我們嘗試用下面的命令
:%s/dog/man/g:%s/man/dog/g
The first command replaces the word “dog” with “man, ” leaving us with the phrase “the man bit the man. ” Then the second command replaces both occurrences of “man ” with “dog, ” giving us “the dog bit the dog. ” Clearly, we have to try harder.
執行第一個命令後,我們得到
“the man bit the man. ”
執行第二個命令後,我們得到
“the dog bit the dog. ”
A two-pass solution is no good, so we need a substitute command that works in a single pass. The easy part is writing a pattern that matches both “dog” and “man ” (think about it). The tricky part is writing an expression that accepts either of these words and returns the other one. Let’s solve this part of the puzzle first。
雙線程的命令不行,我們需要一個替換命令只執行一次。最簡單的部分就是寫一個pattern能夠匹配dog或man。難的地方就在於怎麼寫一個expression,接受這兩個中的其中一個單詞後返回另一個單詞。我們先搞定最難的這部分。
Return the Other Word
We don ’t even have to create a function to get the job done. We can do it with a simple dictionary data structure by creating two key-value pairs. In Vim, try typing the following:
這裡我們不需要用函數來實現,我們可以簡單的通過dictionary資料結果來完成,通過製作兩個key_value對。在Vim中,我們可以這樣:
:let swapper={"dog":"man","man":"dog"} :echo swapper["dog"] man :echo swapper["man"] dog
let建立一個詞典swapper,給swapper輸入man,返回dog,輸入dog,返回man
Match Both Words
Did you figure out the pattern? Here it is:
同時匹配man或dog的pattern為:
/\v(<man>|<dog>)
This pattern simply matches the whole word “man ” or the whole word “dog. ” The parentheses serve to capture the matched text so that we can reference it in the replacement field.
這個pattern匹配全字man或dog。外面的括弧用來擷取匹配到的文本,以便在replacement域中引用它們。
All Together Now
For the replacement, we ’ll have to evaluate a little bit of Vim script. That means using the \=
item in the replacement field. This time, we won ’t bother assigning the dictionary to a variable, we ’ll just create it inline for a single use.
為了進行替換,我們將會採用Vim 指令碼。這就意味著在replacement域中我們會用到\=
。這裡,我們不必把一個詞典賦給一個變數,我們只需線上建立一個。
Normally we could refer to captured text using Vim ’s \1, \2
(and so on) notation. But in Vim script, we have to fetch the captured text by calling the submatch() function (see :h submatch() ).
一般模式下我們通過\1, \2
來引用匹配到的文本,但是在vim 指令碼中,我們只能通過調用函數submatch()來擷取匹配到的文本。
When we put everything together, this is what we get:
我們把前面兩個命令合起來,就可以得到:
/\v(<man>|<dog>):%s//\={"dog":"man","man":"dog"}[submatch(1)]/g
[Practical.Vim(2012.9)].Drew.Neil.Tip95 學習摘要