且构网

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

如何用“ "替换前导空格(仅)在 Vim 中?

更新时间:2022-06-14 23:12:00

我可以通过三种方法来实现所需的编辑看,下面按我个人喜好的顺序列出.

There are three approaches to implement the desired edit that I can see, listed below in the order of my personal preference.

  1. 使用前置原子匹配语法的替换(见 :help \@):

 :%s/\%(^ *\)\@<= /\&nbsp;/g

如果命令的简洁性很重要,可以缩短它使用非常神奇"的模式(见 :help \v)通过改变非捕获组 (:help \%() 到捕获组:

If brevity of the command is crucial, one can shorten it using the "very magic" mode (see :help \v) by changing the non-capturing group (:help \%() to a capturing one:

 :%s/\v(^ *)@<= /\&nbsp;/g

  • 一个两阶段的替换,在前导之后分割一行空格,替换这些空格,然后重新加入该行:

  • A two-staged substitution that splits a line just after the leading spaces, replaces those spaces, and rejoins that line:

     :g/^/s/^ \+/&\r/|-s/ /\&nbsp;/g|j!
    

  • 另一种两步替换,替换每个前导文本中未出现的某些符号的空格,并更改那个符号到 &nbsp;:

     :exe "g/^ \\+/norm!v//e\rr\r" | %s/\r/\&nbsp;/g