First, the ifdef
block needs to be non-greedy, otherwise the fact that the else
block is optional would allow it to capture everything up to #endif
.
Second, .*
will not accept multiple lines by default. You need to enable the single-line option.
This pattern works with your input:
\#ifdef\s+(\S*)[^\n]*
(.*?)
(?:\s*\#else[^\n]*
(.*)
)?\s*\#endif