且构网

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

vim让搜索并替换为增量

更新时间:2023-12-05 15:36:22

:help sub-replace-expression(强调我的想法)

当替换字符串以"\ ="开头时,其余部分将被解释为 表达.

When the substitute string starts with "\=" the remainder is interpreted as an expression.

您不能做自己想做的事;替换字符串要么是子表达式(以\=开头),要么是文字(如果不是).

You cannot do what you want; the replacement string is either a subexpression (when it starts with \=), or a literal (when it does not).

相反,您需要重写子表达式以编程方式连接字符串(:help expr-.):

Instead, you need to rewrite the subexpression to concatenate the string programmatically (:help expr-.):

:let n=[0] | %s/|-\n|/\="BLABLA".map(n,'v:val+1')[0]/g

[0]接受由map生成的数组的内容是必要的,原因有两个:用数组替换将引入不需要的换行符,并使得无法与字符串连接.

[0] to take the content of the array produced by map is necessary for two reasons: replacing with an array will introduce an unwanted newline, and make concatenation with a string impossible.

但是对于您的示例,如果您没有引入除数字之外的任何字符串,则可能没有必要-即,如果您不需要该空格(:help /\zs):

For your example though, it may not necessary, if you are not introducing any string besides the number - i.e. if you don't need that space (:help /\zs):

:let n=[0] | %s/|-\n|\zs/\=map(n,'v:val+1')[0]/g

当然,您可以将两者结合起来,以针对您的特定情况提供完美的去离子化解决方案:

Of course, you can combine the two, for a perfect demoisturised solution to your specific situation:

:let n=[0] | %s/|-\n|\zs/\=" ".map(n,'v:val+1')[0]/g