1

Input

if(statement)
{

to Ouput

if ( statement ) {

I can find the input using

/if(\S\(.*\))

Explanation :

if( is the keyword to be searched , \S to negate whitespace , (.*) for anything in between and ) end bracket.

Need :

Trying to automate coding guideline over code written w/o coding guideline.

EDIT :

:%s/if(\S\(.*\)\S)/if ( \1 )/gc

Came very close but it removes the first character after the 'if(' and last char before ')'

  • Your \Ss eat the first and last character. Can statementcontain whitespace? – D. Ben Knoble Jan 24 at 14:06
6

Your regex was really close. As you mentioned, it cuts off the first and last character of your statement, since \S matches any non-whitespace character. There's no need for \S here. If you remove it, you get really close:

:%s/if(\(.*\))/if ( \1 )/c

This changes your example to:

if ( statement )

If you want to also grab the brace on the next line, you'll need this regex:

:%s/if(\(.*\))\n{/if ( \1 ) {/c

Also, note that I didn't include /g, only /c. This is because /g tells vim to replace every match per line. Without it, vim will search ever line, and replace the first match per line. For this regex, it could only possibly match one per line, so there's no need to tell it to replace every match per line.

There's also some edge cases to consider. For example, what if there were some lines like this:

if ( statement)
{

or

if(statement ) {

Or even

if (   statement   )  {

A more robust regex could be something like:

:%s/if\s*(\s*\(.\{-}\)\s*)\_s*{/if ( \1 ) {/c

Although without seeing your file, I can't guarantee this would catch every case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.