且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在等号周围交换文本

更新时间:2022-12-24 09:25:57

是这样的:

:%s/\([^=]*\)\s\+=\s\+\([^;]*\)/\2 = \1

如果您的代码比示例中显示的更复杂,您可能需要稍微处理一下.

You might have to fiddle with it a bit if you have more complex code than what you have shown in the example.

解释

我们使用 s/find/replace 命令.find 部分让我们知道:

We use the s/find/replace comand. The find part gets us this:

  1. 由除等号以外的任何字符组成的最长字符串,用 [^=]* ...
  2. 表示
  3. ... 后跟一个或多个空格,\s\+(+ 前面的额外的 \ 是 vim 的奇葩)
  4. ... 后跟 = 和任意数量的空格,=\s\+
  5. ... 后跟尽可能长的非分号字符串,[^;]*
  1. longest possible string consisting of anything-but-equal-signs, expressed by [^=]* ...
  2. ... followed by one or more spaces, \s\+ (the extra \ in front of + is a vim oddity)
  3. ... followed by = and again any number of spaces, =\s\+
  4. ... followed by the longest possible string of non-semicolon characters, [^;]*

然后我们放入几个捕获括号来保存我们需要构造替换字符串的内容,那就是 \(stuff\) 语法

Then we throw in a couple of capturing parentheses to save the stuff we'll need to construct the replacement string, that's the \(stuff\) syntax

最后,我们在 s/find/replace 部分使用捕获的字符串em>replace 命令:即 \1\2.

And finally, we use the captured strings in the replace part of the s/find/replace command: that's \1 and \2.