ANTLR4获取ID(获取正确的令牌文本)

时间:2016-01-27 18:43:16

标签: java antlr4

这是我的语法:

        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 : . ; 

和相应的监听器功能:

  public void enterDescription(anamParser.DescriptionContext ctx) {

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

  }

如果我的语法是这样的:

dat:before somethingElse;

字符串ID不包含&#34; somethingElse&#34; 但是&#34; [somethingElse]&#34;

更换线路     String ID = ctx.time()。ID()。toString(); 同     String ID = ctx.time()。ID()。getString();

不会改变这种行为。

访问ID内容的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

我确实过分简化了这个例子:

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

是整个故事。

所以似乎time()。ID()给出了一个数组 type ='before'和type =“'after'。

因此,对ID的正确访问是:

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

和第三种类型('之间') 访问显然是

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

这很好用。

相关问题