Search code examples
regexvimswap

Regex to swap two texts using regex in VIM


Not a regex expert. But, after a bit of search online, I came up with this expression to swap two texts in my file:

%s/(\s*\(&\)\(.*\), \(.*\)\s*);/( \3, \2 );/gc

My initial text:

read( &regVal.mAllBits, getAddr()+offset );

And I want to swap it to:

read( getAddr()+offset, regVal.mAllBits );

As you see above, the requirements are:

  • ignore optional white spaces which comes between each text
  • Remove the & which comes in front of the first text.

I have the \s* at the beginning and end to ignore the white space. But, the problem with it is, the white space before the closing bracket in the statement gets added to match 3. Thus I get the result as:

read( getAddr()+offset , regVal.mAllBits );

Please note the extra white space before the ','. I tried so many things but couldnt resolve it. Can anyone please help me to ignore the whitespace in the pattern matching on my regex statement ?


Solution

  • If you do not want to match whitespace, you must use \S not ., because . will match any character, including whitespace. Regular expressions are always greedy by default, so will match as much as possible.

    %s/(\s*\(&\)\(.*\), \(\S*\)\s*);/( \3, \2 );/gc