I’ve been asked by a co-worker to come up with a regular expression (POSIX syntax) for finding calls to printf(...); — in a c-code file — which aren’t in a #ifdef … #endif scope.
However, seeing as I am only just learning about Regexes at Uni, I’m not completely confident in it.
The scenario would look something like this:
possibly some code
printf(some_parameters); // This should match
possibly more code
#ifdef DEBUG
possibly some code
printf(some_parameters); // This shouldn't match
possibly more code
#endif
possibly some code
printf(some_parameters); // This should also match
possibly more code
Note that a c-file may not contain a #ifdef/#endif statement at all, in which case all calls to printf(); should match.
What I’ve tried so far is this:
(?<!(#ifdef [A-Å0-9]+)).*printf\(.*\);.*(?!(#endif))
…along with playing around with the position (and even inclusion/exclusion) of .*
Any help or hints appreciated.
Regular expressions are not a good way to approach this. They don’t deal well with multi line searches and they are limited in the patterns they can express, e.g. arbitrary nesting is impossible to specify with regexen.
The proper way to tackle this problem is using tools designed to deal with conditional compilation directives in C code. This would be the C preprocessor of your compiler, or a specialized tool like
unifdef:From the manual: