0

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 ?

singleX
  • 375
  • 4
  • 13

1 Answers1

1

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
knittl
  • 246,190
  • 53
  • 318
  • 364
  • Thank you. This works. I knew about the \S option, but for some reason my usage of it was not correct. – singleX May 27 '20 at 17:57
  • The above expression fails when the line is like this: 'read( &regVal.mAllBits, getAddr() + offset );' Please see the space between getAddr + offset. How can I solve this ? – singleX Jun 02 '20 at 19:18
  • 1
    @Manoj In this case it probably works to match on `\([^,]\)\s*` (anything not a comma). But this will break in other scenarios, e.g. `read( bits, nested.call(1, 2) )`. If you want to handle all cases, you'd need to write a parser for whatever non-regular language you are trying to modify. Regular Expressions are not intended for this. Most IDEs probably provide a plugin system with which you can modify a program's AST and generate code from it. – knittl Jun 02 '20 at 19:58