Search code examples
c#regexconditional-compilation

Parsing #ifdef in C# with Regex


I'm trying to parse #ifdef declrations in H files with Regex.

Input example:

#ifdef D_MAIN /* CMNTS */
  #define EXT_D
  some code
#else /* CMNTS */
  #define EXT_D extern 
  some code
#endif /* CMNTS */

So far I've this expression:

\#ifdef\s+(\S*)[^\n]*
([^(.*)]*)
\#else\s+(\S*)[^\n]*
([^(.*)]*)
\#endif

I want to get a list of definitions , each def should take: def name(D_MAIN), the code inside the #ifdef statement and the code inside the #else stmnt.

I'm trying to make the #else part to be optional with ? but not succeed, how can I fix it?

Thanks.


Solution

  • 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