Martin
Martin

Reputation: 125

Regular expression to match C's multiline preprocessor statements

what I need is to match multiline preprocessor's statements such as:

#define max(a,b) \
       ({ typeof (a) _a = (a); \
           typeof (b) _b = (b); \
         _a > _b ? _a : _b; })

The point is to match everything between #define and last }), but I still can't figure out how to write the regexp. I need it to make it work in Python, using "re" module.

Could somebody help me please?

Thanks

Upvotes: 4

Views: 1115

Answers (3)

Aman
Aman

Reputation: 1

I think above solution might not work for:

#define MACRO_ABC(abc, djhg) \
do { \
  int i; \
  /*
   * multi line comment 
   */ \
  (int)i; \
} while(0);

Upvotes: 0

Alan Moore
Alan Moore

Reputation: 75232

This should do it:

r'(?m)^#define (?:.*\\\r?\n)*.*$'

(?:.*\\\r?\n)* matches zero or more lines ending with backslashes, then .*$ matches the final line.

Upvotes: 5

user285321
user285321

Reputation:

I think something like this will work:

m = re.compile(r"^#define[\s\S]+?}\)*$", re.MULTILINE)
matches = m.findall(your_string_here)

This assumes that your macros all end with '}', with an optional ')' at the end.

Upvotes: 0

Related Questions