如何在结果字符串中重复地重复n个匹配的模式

Rod*_*gel 6 regex vim

如何在结果字符串中精确重复n个匹配的模式?

示例如果我有以下文本:

++ '[' -f /etc/bashrc ']'
++ . /etc/bashrc
+++ '[' '[\u@\h \W]\$ ' ']'
+++ '[' -z 'printf "\033]0;%s@%s:%s\007" "${USER}" "${HOSTNAME%%.*}" "${PWD/#$HOME/~}"' ']'
+++ shopt -s checkwinsize
+++ '[' '[\u@\h \W]\$ ' = '\s-\v\$ ' ']'
+++ shopt -q login_shell
+++ '[' 506 -gt 199 ']'
++++ id -gn
Run Code Online (Sandbox Code Playgroud)

现在我想用每个'+'代替3个空格,但它只能在模式的开头发生.我会使用:<range>s/^<pattern> :%s/+/ /g,但如果它在文本的其余部分中有一个"+",我就会搞砸它.

问题:如何在开始时匹配每个+并在结果字符串中重复相同的found +计数?预期:

^   ++$  -> ^         $
^   +++$ -> ^            $
^   +$   -> ^      $
Run Code Online (Sandbox Code Playgroud)

谢谢

dus*_*san 8

试试这个:

:%s/^+*/\=repeat('   ',strlen(submatch(0)))/
Run Code Online (Sandbox Code Playgroud)

submatch(0)包含+该行开头的所有匹配strlen项,对它们进行计数.因此,对于行开头的每个加号,使用插入三个空格repeat.

欲获得更多信息:

:help sub-replace-expression
:help repeat()
:help submatch()
:help strlen()
Run Code Online (Sandbox Code Playgroud)