[antlr-interest] Matching Last Line in ANTLR?

consiliens at gmail.com consiliens at gmail.com
Tue Aug 18 13:08:02 PDT 2009


On 09-08-18 12:43 PM, David-Sarah Hopwood wrote:
> consiliens at gmail.com wrote:
>> The last line, b., doesn't match the MC_INCORRECT token because there's
>> no newline after it. Is there an easy way to match this in ANTLR?
>
> Yes. I had the same problem when matching the end of a //-style comment,
> and solved it like this:
>
> fragment ENDOFLINE
>    : NEWLINE
>    | { input.LA(1) == EOF }?
>    ;
>
> (If this were a non-fragment rule, it would be a problem that it can
> sometimes match no characters, but since it's a fragment, that's OK.)
>

I want to use your solution, however it throws errors about "The 
following alternatives can never be matched: 1" for MC_QUESTION and 
MC_INCORRECT. Shouldn't the below work?

MC_QUESTION  : INT ('.'|')') .* ENDOFLINE;
MC_INCORRECT : LETTER '.' .* ENDOFLINE;
MC_CORRECT   : '*' MC_INCORRECT;

fragment ENDOFLINE : NEWLINE | { input.LA(1) == EOF }?;
fragment NEWLINE : '\r'? '\n';
fragment LETTER  : ('a'..'z'|'A'..'Z');
fragment INT     : '0'..'9'+;


More information about the antlr-interest mailing list