If you want to be sure that you're parsing C comments, you need to confront your model with the C specification. C99 §6.4.9 defines the syntax of comments as follows:
1. Except within a character constant, a string literal, or a comment, the characters /*
introduce a comment. The contents of such a comment are examined only to identify multibyte characters and to find the characters */
that terminate it.
2. Except within a character constant, a string literal, or a comment, the characters //
introduce a comment that includes all multibyte characters up to, but not including, the next new-line character. The contents of such a comment are examined only to identify multibyte characters and to find the terminating new-line character.
This is English prose, not a formal definition, but there is a reasonably clear interpretation in terms of a nondeterministic finite automaton (NFA) that consumes a comment:
- From the initial state,
/
followed by *
enters the in-multiline-comment state, and /
followed by /
enters the in-single-line-comment state.
- From the in-multiline-comment state,
*
followed by /
enters the post-comment state.
- From the in-single-line-comment state, a newline enters the post-comment state.
- Any other character leaves the state unchanged.
Note that to know whether the initial state applies, you have to perform a little more analysis to detect string and character literals.
Once you have an NFA, you can use standard techniques to build a regular expression (I don't see them in the Wikipedia articles, but they should be discussed in textbooks).
If you already have a regular expression and would like to test it, you can compare its generated language with the one from the NFA deduced from the language specification: equality of regular languages is decidable. One way to decide the equality is to build a minimal deterministic automaton for each; if the languages are equivalent, the minimal DFAs will be isomorphic.
(!\*)
intended? Do you mean the more common notation[^*]
? And what's(!*|!/)
? $\endgroup$ – Gilles 'SO- stop being evil' Mar 13 '12 at 16:30