Skip to content
Advertisement

ANTLR4: How to match extra spaces at the beginning of a line?

I tried to match the extra space at the beginning of the line, but it didn’t work. How to modify the lexer rule to match?

TestParser.g4:

JavaScript

TestLexer.g4:

JavaScript

Text:

JavaScript

Java code:

JavaScript

The output is as follows:

JavaScript

The idea is that when a non-option line is encountered in OPTION_MODE, the mode will pop up, and now when there is an extra space at the beginning of the line, it is not matched as expected.

It seems that the n before C.ccc matches NOT_OPTION_LINE causing the mode to pop up? I want C.ccc to match as OPTION, thanks.

Advertisement

Answer

I think you’re making it a bit too complex. As I see it, lines either start as a question ([ t]* [0-9]+) or as an option [ t]* [A-Z]. In all other cases, just ignore the line (. -> skip). That boils down to the following grammar:

JavaScript

A parser grammar could then look like this:

JavaScript

And the Java code:

JavaScript

will then print:

JavaScript

EDIT

Given that you already have target specific code in your grammar, you could just trim the spaces from an option like this (untested!):

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement