regex - How do I make vim substitute repeat until there are no more matches? -


i have file text looks

{\o h}{\o e}{\o l}{\o l}{\o o} {\o w}{\o o}{\o r}{\o l}{\o d} 

i want make text this

{\o hello} {\o world} 

there multiple tools can use solve problem, trying use vim substitutions. far, have

:%s/{\\o \(.\{-}\)}{\\o \(.\{-}\)}/{\\o \1\2}/g 

the patterns here are

.\{-} match characters, non-greedy

{\\o .\{-}} match regex string {\o .*} being non-greedy .*

and \( ... \) creates capture groups backreferencing.

when run substitution once,

{\o he}{\o ll}{\o o} {\o wo}{\o rl}{\o d} 

i could run command 2 more times get

{\o hell}{\o o} {\o worl}{\o d} 

and then

{\o hello} {\o world} 

but love if there way 1 command, i.e., tell vim substitution keep passing on file until there no more matches. seems me ought possible.

does know magic need add achieve this? doesn't there's flag achieves this. maybe trick don't know labels?

sub-replace expression method

you can use sub-replace-expression, \=, execute second substitution inside replacement part of :s

:%s/\({\\o \s}\)\+/\='{\o '.substitute(submatch(0), '{\\o \(\s\)}', '\1', 'g').'}'/g 

the basic idea capture "word", e.g. {\o h}{\o e}{\o l}{\o l}{\o o}, , second substitution on captured "word", submatch(0). second substitution remove starting {\o , trailing } via substitute(submatch(0), '{\\o \(\s\)}', '\1', 'g'). leaves letters, hello in example. once every letter extracted word add in starting {\o , trailing }.

for more see:

:h :s :h sub-replace-expresion :h substitute( :h submatch( :h literal-string :h /\s 

two substitutions

you can use 2 separate substitutions. 1 remove {\o , }. other substitution add them in, word-wise time.

:%s/{\\o \(.\)}/\1/g :%s/\s+/{\\o &}/g 

this arguably easier method assuming not have text mixed in other text should not in format.

you can in 1 command using |:

:%s/{\\o \(.\)}/\1/g|%s/\s+/{\\o &}/g 

Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -