Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to exactily repeat the n matched pattern in result string

Tags:

regex

vim

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

like image 938
Rodrigo Gurgel Avatar asked Aug 07 '12 13:08

Rodrigo Gurgel


People also ask

How do you repeat a pattern in regex?

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.

Why * is used in regex?

* - means "0 or more instances of the preceding regex token"

What does the plus character [+] do in regex?

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 .


1 Answers

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()
like image 121
dusan Avatar answered Sep 21 '22 16:09

dusan