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.
\S
s eat the first and last character. Canstatement
contain whitespace?