How to exactly repeat the n matched pattern in result string?
Example if I have the folowing text:
++ '[' -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
Now I want to substitute every '+' for 3 spaces, but it can only happen at the begining of the pattern. I would use :<range>s/^<pattern>
:%s/+/ /g
, but if it there were a '+' in the rest of the text I would simply mess it up.
The question: How to match every + at begining and repeat the same count of found + in the result string? expected:
^ ++$ -> ^ $
^ +++$ -> ^ $
^ +$ -> ^ $
Thanks
A repeat is an expression that is repeated an arbitrary number of times. An expression followed by '*' can be repeated any number of times, including zero. An expression followed by '+' can be repeated any number of times, but at least once.
* - means "0 or more instances of the preceding regex token"
Inside a character class, the + char is treated as a literal char, in every regex flavor. [+] always matches a single + literal char. E.g. in c#, Regex. Replace("1+2=3", @"[+]", "-") will result in 1-2=3 .
Try this:
:%s/^+*/\=repeat(' ',strlen(submatch(0)))/
submatch(0)
contains all the matched +
at the start of the line, strlen
counts them. So for every plus sign at the start of the line three spaces are inserted using repeat
.
For more information:
:help sub-replace-expression
:help repeat()
:help submatch()
:help strlen()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With