Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to regex in Vim

Tags:

regex

vim

I want to add some text before each return For example we have :

void* foo (){
   if (something){ 
   return A;
   }
do_something;
// That return word may be ignored, because it's comment
do_something;
returns(); //It may ignored to
return ;
}

I need :

void* foo (){
   if (something){
   END;
   return A;
   }
do_something;
// That return word may be ignored, becouse it's comment
do_something;
returns(); //It may ignored to
END;
return ;
}

I can't build regex for search request. It may looks like "

return"< some text here started with space symbol, or nothing >;<endline>

How I can make it in VIM?

like image 714
Stepan Loginov Avatar asked Jan 19 '26 11:01

Stepan Loginov


2 Answers

Using hold registers is an easy way to do this:

%s/^\(\s*\)\(return\>.*\)/\1END;\r\1\2/g

The meanings:

%s - global substitute
/  - field separator
^  - start of line
\( - start hold pattern
\s - match whitespace
*  - 0 or more times
\) - end hold pattern
\> - end of word boundary (prevent returns matching return)
.  - match any character
\1 - recall hold pattern number 1
\2 - recall hold pattern number 2
\r - <CR>
g  - Replace all occurrences in the line
like image 155
cforbish Avatar answered Jan 22 '26 09:01

cforbish


You may use the global command as follows:

:g/^\s*return\>/normal OEND;

It searches for lines having any number of whitespace and the word return, executes the command O and adds the "END;"

Bonus feature the END; is 'auto indented'.

like image 39
Tassos Avatar answered Jan 22 '26 07:01

Tassos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!