Search code examples
regexvimex

Vim - regex for changing bool variable checking


I am working on a C project an I want to change all bool-variable checking from

if(!a)

to

if(a == false)

in order to make the code easier to read(I want to do the same with while statements). Anyway I'm using the following regex, which searches for an exclamation mark followed by a lowercase character and for the last closing parenthesis on the line.

%s/\(.*\)!\([a-z]\)\(.*\))\([^)]+\)/\1\2\3 == false)\4/g

I'm sorry for asking you to look over it but i can't understand why it would fail.

Also, is there an easier way of solving this problem and of using vim regex in general?


Solution

  • One solution should be this one:

    %s/\(.*\)(\(\s*\)!\(\w\+\))/\1(\3 == false)/gc
    

    Here, we do the following:

    %s/\(.*\)(\(\s*\)!\(\w\+\))/\1(\3 == false)/gc
    
       \--+-/|\--+--/|\---+--/|
          |  |   |   |    |   finally test for a single `)`.
          |  |   |   |    (\3): then for one or more word characters (the var name).
          |  |   |   the single `!`
          |  |   (\2): then for any amount of white space before the `!`
          |  the single `(`
          (\1): test for any characters before a single `(`
    

    Then, it's replaced by the first, third pattern, and then appends the text == false, opening and closing the parentheses as needed.