我建议您将“数字对”保留在单独的规则中:
语法分析器
transitions
: 'transitions' '=' INT pair+ ';' -> ^(TRANSITIONS INT pair+)
;
pair
: '(' INT ',' INT ')' -> ^(PAIR INT INT)
;
树语法
transitions
: ^(TRANSITIONS INT pair+) {System.out.println("transitions.INT=" + $INT.text);}
;
pair
: ^(PAIR a=INT b=INT) {System.out.println("pair=" + $a.text + ", " + $b.text);}
;
编辑
快速演示:
grammar T;
options {
output=AST;
ASTLabelType=CommonTree;
}
tokens {
TRANSITIONS;
PAIR;
}
parse
: transitions EOF!
{
CommonTree root = $transitions.tree;
int count = root.getChildCount();
Tree child1 = root.getChild(0);
Tree child2 = root.getChild(1);
Tree child3 = root.getChild(2);
Tree child4 = root.getChild(3);
System.out.println("root=" + root.getToken().getText() + " has " + count + " child nodes:");
System.out.println(" - child1=" + child1.toStringTree());
System.out.println(" - child2=" + child2.toStringTree());
System.out.println(" - child3=" + child3.toStringTree());
System.out.println(" - child4=" + child3.toStringTree());
String secondValueFromLastPair = child4.getChild(1).getText();
System.out.println("\nsecondValueFromLastPair=" + secondValueFromLastPair);
}
;
transitions
: 'transitions' '=' INT pair+ ';' -> ^(TRANSITIONS INT pair+)
;
pair
: '(' INT ',' INT ')' -> ^(PAIR INT INT)
;
INT : '0'..'9'+;
SPACE : ' ' {skip();};
如果您现在解析 input "transitions = 3(5,0) (5,1) (5,2);"
,您会看到以下内容被打印到控制台:
root=TRANSITIONS 有 4 个子节点:
- 孩子1=3
- child2=(对 5 0)
- child3=(对 5 1)
- child4=(对 5 1)
secondValueFromLastPair=2