antlrantlr4

how to write a lexer rule in antlr4?


my antlr4 hello world grammar as below

grammar Hello;
r
    : 'hello' [a-z]+ EOF
    ;
WS
    : [ \t]+ -> skip
    ;

and then i use 'antl4 Hello.g4' command in cmd, but it throw exceptions:

error(50): Hello.g4:3:11: syntax error: 'a-z' came as a complete surprise to me while looking for rule element
error(50): Hello.g4:4:1: syntax error: mismatched input ';' expecting COLON while matching a lexer rule

but i found this code works well:

grammar Hello;
r
    : 'hello' ID EOF
    ;
ID  :
    [a-z]+
    ;
WS
    : [ \t]+ -> skip
    ;

could anyone help me please? thank you very much!


Solution

  • A character class, like [a-z]+, only works in lexer rules, not parser rules. That is why you get an error when you use it in r, but not when you use it inside ID.