Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ANTLR4: zero or one times

I'm working on defining a grammar using ANTLR4 and Java. For Integers, I want a number that mat be preceeded by a minus sign. I know it is possible to do it like this:

integer: '-' (DIGIT)* | DIGIT* ;

But I was wondering if there is a symbol (similar to the *) that assures a the minus sign occurs zero or one time:

integer: ('-')<some symbol here> (DIGIT)* ;
like image 759
Elias Avatar asked Feb 15 '18 14:02

Elias


People also ask

What is Antlr4 used for?

What is ANTLR? ANTLR (ANother Tool for Language Recognition) is a powerful parser generator for reading, processing, executing, or translating structured text or binary files.

What are lexer rules?

Rules defined within a lexer grammar must have a name beginning with an uppercase letter. These rules implicitly match characters on the input stream instead of tokens on the token stream. Referenced grammar elements include token references (implicit lexer rule references), characters, and strings.

How does Antlr lexer work?

An ANTLR lexer creates a Token object after matching a lexical rule. Each request for a token starts in Lexer. nextToken , which calls emit once it has identified a token. emit collects information from the current state of the lexer to build the token.

Why should a start rule end with EOF in an Antlr grammar?

You should include an explicit EOF at the end of your entry rule any time you are trying to parse an entire input file. If you do not include the EOF , it means you are not trying to parse the entire input, and it's acceptable to parse only a portion of the input if it means avoiding a syntax error.


1 Answers

Yes, it's the ?, which means zero or once (optional). Also, the * means zero ore more. You probably want + which means once or more:

integer : '-'? DIGIT+ ;
like image 58
Bart Kiers Avatar answered Sep 20 '22 01:09

Bart Kiers