0

I am trying to write one regexp to match C preprocessor commands in C program. I wonder if you can give me some suggestions?

Thank you so much in advance.

3
  • 1
    How about this one stackoverflow.com/questions/11826016/… Commented Jul 31, 2013 at 10:14
  • regexp in which language/utility ? Commented Jul 31, 2013 at 10:16
  • 2
    One does not simply parse C using regexes. Nor can you parse HTML using awk. This didn't change recently. Commented Jul 31, 2013 at 10:18

3 Answers 3

1

That would be

 grep '^[[:blank:]]*#'

Note that this will only grep the first line of a multi line preprocessor directive (continued with backslash newline).

Sign up to request clarification or add additional context in comments.

2 Comments

Overall wisdom notwithstanding, I approve this answer and I wrote a preprocessor. The entire requirements for a directive are that it goes from a # or %: token following a newline, to just before the next newline. Whether the inside of the directive is well-formed is another matter. The other shortcoming of this approach is that it doesn't allow a comment before the #, but seriously who cares.
@Jens Thank you Jens. I will have a try later.
0

May be this: (not too exact though)

\s*#\s*(define|error|import|undef|elif|if|include|using|else|ifdef|line|endif|ifndef|pragma)\s*\S*

You can use cpp and pass the option -dM to list out all defined macros.

cpp -dM test.c

3 Comments

can have space after #
That's not working. Some directives don't need anything to follow, and there's even the empty directive just consisting of '#'. Then, #import and #using are not C directives.
@AnttiHaapala Thank you for your reply. I will have a try.
0

This regex illustrates how the backslash \ newline can be integrated using recursive regex:

#(?<line>[^#].*?(\n|(\\[^\n]*\n(?&line))))

Hope this helps.

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.