[Practical.Vim(2012.9)].Drew.Neil.Tip95 学习摘要

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能够匹配dogman。难的地方就在于怎么写一个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

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。