Search code examples
antlrantlr3antlrworks

How to get the Text of a Lexer Rule


I have a Antlr Grammar Lexer Rule Like this,

Letter
    :  '\u0024' | '\u005f'|
       '\u0041'..'\u005a' | '\u0061'..'\u007a' | 
       '\u00c0'..'\u00d6' | '\u00d8'..'\u00f6' | 
       '\u00f8'..'\u00ff' | '\u0100'..'\u1fff' | 
       '\u3040'..'\u318f' | '\u3300'..'\u337f' | 
       '\u3400'..'\u3d2d' | '\u4e00'..'\u9fff' | 
       '\uf900'..'\ufaff'
    ;

Name : Letter (Letter | '0'..'9' | '.' | '-')*;

I want to get the String Value of Name. How can I do it?


Solution

  • from a parser rule:

    rule
     : Name {String s = $Name.text; System.out.println(s);}
     ;
    

    or

    rule
     : n=Name {String s = $n.text; System.out.println(s);}
     ;
    

    from the lexer rule itself:

    Name 
     : Letter (Letter | '0'..'9' | '.' | '-')*
       {String s = $text; System.out.println(s);}
     ;