简体   繁体   中英

ANTLR4 get ID (get correct token text)

Here is my grammar:

        grammar Text;

        prog: description+;

        description: 
            type='dat' COLON  time COLON ';'
        ;

        time:
               type='before ' ID 
             | type='after ' ID
        ;


        STRING : '"' ('""'|~'"')* '"' ; // quote-quote is an escaped quote


        LINE_COMMENT
            : '//' (~('\n'|'\r'))* -> skip;

        COMMENT : '/*' .*? '*/' -> skip;
        LE: '<';
        MINUS: '-';
        GR: '>';  
        COLON      : ':' ;
        HASH: '#';
        EQ: '=';
        SEMI: ';';
        SPACE: ' ';
        COMMA: ','; 
        AND:  [Aa][Nn][Dd];
        NUMBER: [0-9];
        ID: [a-zA-Z][a-zA-z0-9]+;
        WS  :   [ \t\n\r]+ -> channel(HIDDEN);
        ANY_CHAR : . ; 

and the corresponding listener function:

  public void enterDescription(anamParser.DescriptionContext ctx) {

      String ID = ctx.time().ID().toString();
      System.out.println("ID " + ID);

  }

If my syntax is something like this:

dat:before somethingElse;

the String ID does not contain "somethingElse" but "[somethingElse]"

Replacing the line String ID = ctx.time().ID().toString(); with String ID = ctx.time().ID().getString();

does not change this behavoir.

What is the correct way to access the content of ID?

I did oversimplify the example a bit:

time:
           type='before ' ID 
         | type='after ' ID
         | type='between ' ID ' AND ' ID
    ;

is the whole story.

So it seems that time().ID() gives an array also for type='before ' and type="'after '.

So the correct access for the ID is:

String ID = ctx.time().ID(0).toString();

and for the third type ('between ') the access obviously is

String ID2 = ctx.time().ID(1).toString();

This works fine.

'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM