[antlr-interest] Match token {n} times

Gary Miller gary at sumwise.com
Sun Aug 28 16:50:37 PDT 2011


Hi Jonne,

Take a look at "The Definitive ANTLR Reference"
http://pragprog.com/book/tpantlr/the-definitive-antlr-reference

Page 294 The Three Semantic Predicate Variations

"
Consider the problem of matching an element at most four times.

data: BYTE BYTE BYTE BYTE
| BYTE BYTE BYTE
| BYTE BYTE
| BYTE
;

validating semantic predicate.
data: ( b+=BYTE )+ {$b.size()<=4}?
;

gated semantic predicate
data
@init {int n=1;} // n becomes a local variable
: ( {n<=4}?=> BYTE {n++;} )+ // enter loop only if n<=4
;
"

There are also disambiguating semantic predicate {«expression»}?
before the match.

Hope this helps.

Regards
Gary

On Mon, Aug 29, 2011 at 12:33 AM, The Researcher
<researcher0x00 at gmail.com> wrote:
>> On Sun, Aug 28, 2011 at 3:20 PM, Jonne Zutt <jonne.zutt.ml at gmail.com>
>> wrote:
>>
>> > Dear all,
>> >
>> > Is it possible with antlr to match a token exactly n times?
>> > Something like the following:
>> >
>> > ACCOUNT : NUMBER{8};
>> >
>>
>
> Hi Jonne,
>
> Bart is correct in that matching a exact quantity is not built in to ANTLR,
> and most likely never will. Exact quantities is a feature of Regular
> Expressions.
>
> If you are willing to work with gated semantic predicates it can be done.
>
> >From the grammars page http://www.antlr.org/grammar/list download the Java
> .class file grammar and take a look at classfile.g; specifically rule for
> constant_utf8_info.
>
> I believe it is a older v 2.x grammar but will put you in the ball park.
>
> With this I was able to parse binary files, but eventually took a different
> route that didn't use ANTLR.
>
> If you are going to be doing lots of these types of rules in a single
> grammar then you should really step back and consider if you want to abuse
> ANTLR, and instead take a different approach.
>
> Good Luck,
> Eric
>
> List: http://www.antlr.org/mailman/listinfo/antlr-interest
> Unsubscribe: http://www.antlr.org/mailman/options/antlr-interest/your-email-address
>


More information about the antlr-interest mailing list