ANTLR 4 how to parse comments

antlr4

Solution

When in doubt, see what someone else did ;)

There are some ready-made grammars for different languages, more or less working.

So I look in Java's grammar and see:

COMMENT
: '/*' .*? '*/' -> skip
;
LINE_COMMENT
: '//' ~[\r\n]* -> skip
;

So your general idea seems to be correct. I'm guessing that the problem lies somewhere else. Can you provide sample input you test on and your grammar (relevant parts)?

Problem

I am parsing a SQL like language and I am having trouble parsing comments. The idea is to ignore them. I have these rules: ``` NEWLINE: '\r'? '\n' -> skip WS : [ \t]+ -> skip ``` How can I ignore: - Everything that is between '--'or '#' and the next '\n' - Everything between '/' and '/' (slash + asterisk untill asterix + slash - the asterisk somehow gone). I tried something like this before the WS and the NEWLINW: ``` COMMENT1 : ('--'|'#') ~'\n'* -> skip; ``` didn't work - I got: ``` line 1:115 missing ';' at '<EOF>' ``` probably something because it didn't go with my main rule: parse : (statments (';')+)* EOF; Can anyone help me? Regards idob

Original source