Search code examples
javajavacc

How to have a range for a number


I'm using javaCC to generate my parser. But I want to have a date with this format : "01/02" or "05/12" or "30/11"

TOKEN :
{
  < CONSTANT : (< DIGIT >)+ >
| < STRING : ( ["A"-"Z","a"-"z"] )+ >
| < #DIGIT : [ "0"-"9" ] >
| < SLASH: "/" >
}

I have something like that :

(< CONSTANT > <SLASH > < CONSTANT >)

But it accept 999/888 ... How can i accept only 0-31 for the left side of slash, and 0-12 for the right side of slash

Thanks a lot for your help


Solution

  • I'd probably handle this in the parser roughly as follows

    void date() throws AnException : {
        Token t ;
        int m;
        int d ;
    }{
        t=<CONSTANT>   { d = Integer.parse(t.image) ; }
        <SLASH>
        t=<CONSTANT>   { m = Integer.parse(t.image) ; }
        {   if( m > 12 ) throw AnException() ;
            if( d > 31 ) throw AnException() ;
        }
     }