Regular expression to match C multi-line preprocessor statements

I need to match multi-line preprocessor instructions, such as:

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

The dot should match everyone #defineand last }), but I still can't figure out how to write a regex. I need it to work in Python using the "re" module.

Can someone help me?

thank

+3
source share
3 answers

This should do it:

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

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

+3
source

I think something like this will work:

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

, '}', ')' .

0

I think that the solution may not work:

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

Source: https://habr.com/ru/post/1736475/


All Articles