You first want to use non-greedy quantifiers, removingmake the optional part from+ operators non-greedy. Then instead of making the third capturing group and placingoptional, simply place that group inside of the nonNon-capturing group leaving the Non-capturing group optional.
/{\?if ([^{}]+)}(.+?)(?:{\?else}(.+?))?{\?endif}/g