Spektor
Spektor

Reputation: 535

ANTR3 set the number of accepted characters for a token

I have to create a Lexer which will accept for example an integer only if it has a maximum of 8 digits. Is here an alternative to do it rather than just writing it like this?

INTEGER : (DIG | DIG DIG | DIG DIG DIG | ...)

Upvotes: 1

Views: 140

Answers (1)

Bart Kiers
Bart Kiers

Reputation: 170227

This can be done using a Gated Semantic Predicates like this:

INTEGER
@init{int n = 1;}
  :  ({n <= 8}?=> DIGIT {n++;})+
  ;

fragment DIGIT : '0'..'9';

Details about this kind of predicate, see: What is a 'semantic predicate' in ANTLR?

Upvotes: 2

Related Questions