[antlr-interest] Specifying limit on number of digits in the Grammar in ANTLR

Bharath R bharath.mail.list at gmail.com
Sun Apr 29 11:12:37 PDT 2007


Hi,

     Thanks for this solution. I've upgraded to V3 and using the
solution-3 given below. I'm now successfully able to parse for 5 digit
numbers.
  i.e i've used the following:

  ID: ( d+=DIGIT)+ {$d.size() <= 5}?

  Next step, I want to display the detected number. I've written the
following to display the entire number detected.

  id: (d+=DIGIT)+ {$d.size() <= 5}?
    { String resultStr = new String();
   	  java.util.Iterator iter = $d.iterator();
   	  while(iter.hasNext())
   	  {
   	 	Token tok = (Token)iter.next();
   	 	resultStr+=tok.getText();
   	 }

      System.out.println("Digit="+resultStr);
    }
    ;

DIGIT :	('0'..'9')
    ;


   Is this the right way to display detected number? Is there any
simpler way to achieve this?

Thanks for your help.


Regards,
Bharath




>This problem is well described in the new Ter book (page 292, in my
last beta version).

>In fact there is 3 ways to do it:

>1) Simple context-free grammar

>ID: DIGIT DIGIT DIGIT DIGIT DIGIT
>| DIGIT DIGIT DIGIT DIGIT
>| DIGIT DIGIT DIGIT
>| DIGIT DIGIT
>| DIGIT
>;

>2) Verify the size using actions

>ID: ( d+=DIGIT)+ {if ( $d.size() > 5 ) <<error action>> }?
>;


>3) Using validating semantic predicate

>ID: ( d+=DIGIT)+ {$d.size() <= 5}?
>;


>What is the best solution? It always depends (on my point of view) but
>if sometimes you will need to change your grammar to accept 7 instead
>of 5 digits? I would choose the third one.

>Alexandre Porcelli


On 4/26/07, Bharath R <rbharath24 at yahoo.com> wrote:
> Hi,
>
>       I'm a newbie to ANTLR.
>         I am trying to write a simple parser, that accepts number
whose
> number of digits vary from 1 to 5.
>
>     Below is the ABNF format
>  ID: 1*5(DIGIT)
>  DIGIT: '0'..'9'
>
>  i.e the ID can be any number varying from a 1 digit number to a max
of
> 5digit number. Each digit varying between 0 and 9.
>  How do I achieve this in ANTLR? I have been trying to write an
equivalent
> EBNF format but without success.
>  Thanks for you help.
>
> Regards,
> Bharath
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/antlr-interest/attachments/20070429/4ed56415/attachment.html 


More information about the antlr-interest mailing list