Srikar
Srikar

Reputation: 371

I need to parse a number by 4 digits in antlr4

I just started out using antlr4 I just want to write a grammar that can parse through a number series but only select 4 digits at a time

for example, I have a number 1234567891234567 then I want it to parse first 4 digits into 1 token the next into another and the next into another so that I get 4 different 4 digit tokens.

token1 = 1234,
token2 = 5678,
token3 = 9123,
token4 = 4567,

can anyone help me write a grammar for this

   grammar TEST;

    /*
     * Parser Rules
     */

    test             :   (example+ EOF);
    example          :   digit COMMA digit2 NEWLINE;
    digit            :   SINGLE+;
    digit2           :   QUADRUPLE+;


    /*
     * Lexer Rules
     */

     SINGLE:
        INT 
   ;

    QUADRUPLE:
       INT INT INT INT
   ;

   fragment INT:
       [0-9]
    ;
   NEWLINE    : ('\r'? '\n' | '\r')+ ;
   COMMA      : ',';

enter image description here

here's the grammar I have written what I need it to print single digits as tokens 1st and then after a comma I need the numbers to be printed as 4digits in tokens please check the attached image and help me out

Upvotes: 0

Views: 1386

Answers (1)

Raven
Raven

Reputation: 3526

The respective lexer rule would look like this:

QUADRUPLE:
    INT INT INT INT
;

fragment INT:
    [0-9]
;

So the key to this problem is to renounce using one of ANTLR's "repeating-operators" (*, +) and simply write the repetition by hand so that it matches exactly the desired count.

Upvotes: 1

Related Questions