[antlr-interest] Simple way to get the text that matched

Bryan Ewbank ewbank at gmail.com
Wed Nov 1 10:39:36 PST 2006


Hi Rick,

You're pretty close.  In the actions, you need a "#" prefix on t1 and t2 to
tell ANTLR that these names refer to the subrules.  Also, remove the parens so
that t1 and t2 refer to the strings themselves.  This is what it will be, more
or less:

   // i did not compile this, but it should be very close :-)
   parserRule1
      : t1:"keyword1" parserRule2
      {
       printf("parserRule1 got a %s from parserRule2\n",
          #t1.getText());
      }
      ;
   parserRule2
      : t2:"keyword2" LEXER_RULE_1
      {
       printf("parserRule2 got a %s from the lexer\n",
          #t2.getText());
      }
      ;
   LEXER_RULE_1 : "sometoken";

A related beginners caution: If you want to consume an entire file, make sure
you terminate your main production with EOF; without the EOF match, then it
will only parse the matching prefix of the file.

On 11/1/06, Rick Morgan <r.morgan at verizonbusiness.com> wrote:
> Could someone reply with the simplist way to return the text matched by any
> parser rule?
>
> parserRule1
>  : t1:("keyword1" parserRule2)
>  {
>     printf("parserRule1 got a %s from parserRule2\n",
>        t1.getText());
>  }
>  ;
> parserRule2
>  : t2:("keyword2" LEXER_RULE_1)
>  {
>     printf("parserRule2 got a %s from the lexer\n",
>        t2.getText());
>  }
>  ;
> LEXER_RULE_1 : "sometoken";


More information about the antlr-interest mailing list