1

I want to find the #else case for certain a C preprocessor define.

Example:

#if defined(my_define)
  // multiple 
  // lines 
  // of 
  // code
#else
  // multiple 
  // lines 
  // of 
  // code
#endif

Or

#if defined (my_define)
  // same as above from here 

But I do not want to match a case without #else:

#if defined(my_define)
  // multiple 
  // lines 
  // of 
  // code
#endif

I don't care for nested #ifs, just the cases above.

I tried starting with

defined..?my_define.(\r\n|\r|\n)?

I don't know how to handle the arbitrary number of lines in between the directives.

2
  • 1
    While it is possible, it looks really ugly. Commented Mar 15, 2017 at 9:52
  • Thank you. I slightly changed it to #if defined..?my_define\b(?:(?!#(?:end)?if)[\s\S])*#else(?:(?!#(?:end)?if)[\s\S])*#endif to include the defines name (and whitespace) and it works flawless :-) Feel free to write an answer, so I can mark it as solved. Commented Mar 15, 2017 at 13:06

1 Answer 1

1

You may use a tempered greedy token solution here:

#if defined..?my_define\b(?:(?!#(?:end)?if)[\s\S])*#else(?:(?!#(?:end)?if)[\s\S])*#endif

See the regex demo

Details:

  • #if defined - a literla char sequence
  • ..? - any 1 or 2 chars other than line break char
  • my_define\b - a whole word my_define
  • (?:(?!#(?:end)?if)[\s\S])* - a tempered greedy token matching any char that is not a starting point for an #endif or #if literal char sequence
  • #else - a literal char sequence
  • (?:(?!#(?:end)?if)[\s\S])* - same as above
  • #endif - a literal char sequence
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.