Pregunta

I try to use regex in Delphi to solve C PreProcessor directives. As an example I have some textfile which contains

#define test
#ifdef test
foo

#else

bar
#endif

What I want is to know in my fist match is, if it is ifdef or ifndef.
In my second match, I want to get, what should (not) be defined.
Number three would be everything until either #else or #endif.
If it was #else, #else should be the content of match 4.
Match 5 would then be content again and match 6 will only hold an #endif
BTW. I do not care about \n or \r in the matches. They will be filtered.

My first try was the following regex:

/#(ifn?def) +(.*)\n(.*)(#else)?(.*)?(#endif)/si

which did absolutely not work. And no matter what I try, I can only get #ifdef and the key which should (not) be defined + everything else in the second match.

Is there a solution for regex? Is regex the best solution for this kind of thing?

¿Fue útil?

Solución

Since subexpressions 4 and 5 are optional, the greedy second and third subexpressions end up gobbling everything, even if #else appears in your input. You need to make them non-greedy. To ensure that subexpression 5 is only filled when subexpression 4 matches, put one inside the other. You'll end up with this:

/#(ifn?def) +(.*?)\n(.*?)(#else(.*))?(#endif)/si

I would make subexpression 4 a non-capturing group, and I wouldn't bother grouping subexpression 6 at all since the contents of both can be inferred by context.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top