在 Antlr4 中解析 C 预处理器语句,以注释结尾

Parse C preprocessor statement, ending with a comment, in Antlr4

我正在尝试为以下行创建语法规则:

#define FLAG /* this is a comment */

#define FLAG // this is another

这是我当前的规则:

DefineDirective
    :   '#' Whitespace? 'define' ~[\r\n]* Newline
        -> channel(2)
    ;

但是,它也会消耗评论。我需要做一些检查,如果该行包含“//”或“/*”,在这种情况下会中断,但我不知道该怎么做。有人有想法吗?

找到一个可行的解决方案,所以分享它:

DefineDirective
    :   '#' Whitespace? 'define' ((~[/\r\n]) | ('/' ~('*'|'/')))*
        -> channel(2)
    ;

(~[/\r\n]) = 匹配除换行符和 /

之外的任何内容

('/' ~('*'|'/')) = 匹配 /,但前提是它后面没有 * 或另一个 /