简体   繁体   中英

ANTLR4 + Python - how to access fragment tokens (sub tokens) from the listener?

How can I access the token MONTH_NAME or DIGITS from the listener using the following grammar:

date : DATE_BULK;
DATE_BULK :  DIGITS SEPARATOR DIGITS SEPARATOR DIGITS
          |  DIGITS WHITE_SPACE MONTH_NAME WHITE_SPACE DIGITS ;
fragment MONTH_NAME : 'Jan' |
                      'Feb' |
                      ;

In the listener I can do:

def exitDate(self, ctx):
    dateBulk = ctx.DATE_BULK().getText()

But this gives the whole date which I then have to parse manually using regular expression or other methods.

  • PS: I can't get rid of the dummy DATE_BULK and define date using the rules directly due to structure constraints in my overall grammar which is kinda complex.

I can't get rid of the dummy DATE_BULK and define date using the rules [...]

Then the answer is simple: you can't. DATE_BULK is one token and can't be separated in your parser (other than using Python's substring-functions, of course).

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