Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim matching everything except a character at the beginning of a line

Tags:

regex

vim

I have extensively searched for an answer for this and I can't find it anywhere. I would like to replace all code in a function block with just one line(using search and replace) or some other command. I would also like to be able to do this for multiple functions throughout the entire file.

I have a block of code like this...

{
some code
more code...
many lines of random code
}

I would like to replace everything inside the curly braces with one line of code such as:

{
return STATUS_OK;
}

I tried something like,

%s/^{_[^}]+/\treturn STATUS_OK;/g

but this stops at the first } rather than the first } at the beginning of a line.

I tried this

%s/^{_[^^}]+/\treturn STATUS_OK;/g

in order to stop at the first } at the beginning of a line but this does not work for some reason. Any ideas? Thanks.

like image 991
dbzVT8 Avatar asked Jan 11 '23 23:01

dbzVT8


1 Answers

This regex matches the outer most curlies without considering the function name:

 %s/^{\(\(\s\+}\)\|[^}]\|\_s\)*/{\treturn STATUS_OK;/g

Breakdown:

^{  # match a curly at the beginning of a line
\(  # group these alternations.... either match
     \(\s\+}\) \|  # whilespace followed by a closing curly 
                   # (to get rid of internal blocks) or ..
     [^}]      \|  # match a non curly, or ..
     \_s           # match newlines and whitespaces
 \)*               # match the alternation as long as you can
like image 66
perreal Avatar answered Jan 31 '23 08:01

perreal