Note: I am not looking for a working substitution for my command (allready have that), but for an explanation.

I have the following code:

include <stdio.h>

char ga[] = "abcdefghijklm";

void my_array_func(char ca[10]);
void my_pointer_func(char *pa);

int main()
   /* code */

   return 0;

and use the following search on it:

/^$\n\(^.*\n\)\{-}\ze$\nint main

Which should match:

void my_array_func(char ca[10]);
void my_pointer_func(char *pa);

But it doesn't. It does match all possible lines above. In this case:

char ga[] = "abcdefghijklm";

void my_array_func(char ca[10]);
void my_pointer_func(char *pa);

If I add more lines which are fitting to the pattern it matches them too. So it behaves exactly the same if I replace \{-} with *.

If I use the count directly (\{2} instead of \{-}) I get the result as expected.


This greedyness comes from * that is inside parenthesis. It matches also empty lines. If you change that to \+ it should work as you expect it to.

  • hmm interesting, \+ works as you said, but replacing * with \{-} does not work (I tried that before, because I suspected it was the *). \+ actually should not work, it is greedy (see :h \+) Aug 13 '18 at 10:33
  • Yes, it is greedy, but it excludes line 4 from the match. Replacing inner part of parenthesis with ^[^=]*\n will also work as expected with the advantage that you can have empty lines in between function declarations. So it's all about that empty line 4, since the regexp is not designed to only match function declarations.
    – grodzik
    Aug 13 '18 at 10:57
  • 1
    A comment from SO, which explains why \{-} is not working (from sidyll): being non-greedy doesn't mean the shortest possible match. It just means the shortest continuation or replication after it started matching that satisfies the next condition. Yours begins matching earlier than his, and greediness does not apply to the start but to the replication of the atom. To the engines eyes: you start matching and if it matches, jump to the next condition. If the next condition is replicate this in a non-greedy fashion, it will replicate until the next condition meets. It won't change the start Aug 14 '18 at 5:40

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.