ANTLR production rules can have one or more return types that you can reference within a loop (a (...)*or (...)+). So, let's say you want to print every text Tthat matches the rule antExp. This can be done as follows:
expr
: (antExp {System.out.println($antExp.str);} )+
;
antExpr returns [String str]
: '{' T '}' {$str = $T.text;}
;
T : 'foo';
The same principle holds, for example, in grammar number 2:
expr : antExpr;
antExpr : '{' (T {System.out.println($T.text);} )* '}' ;
T : 'bar';
EDIT
, . , :
grammar T;
parse
: ids {System.out.println($ids.firstId + "\n" + $ids.allIds);}
;
ids returns [String firstId, List<String> allIds]
@init{$allIds = new ArrayList<String>();}
@after{$firstId = $allIds.get(0);}
: (ID {$allIds.add($ID.text);})+
;
ID : ('a'..'z' | 'A'..'Z')+;
SPACE : ' ' {skip();};
"aaa bbb ccc" :
aaa
[aaa, bbb, ccc]