Skip to main content
1 of 2
hwnd
  • 70.9k
  • 4
  • 100
  • 135

You want to use non-greedy quantifiers, removing the optional part from the third capturing group and placing that group inside of the non-capturing group.

/{\?if ([^{}]+)}(.+?)(?:{\?else}(.+?))?{\?endif}/g 

Live Demo

hwnd
  • 70.9k
  • 4
  • 100
  • 135