如何在ANTLR中设置规则选项计数 [英] How to set a rule option count in ANTLR
问题描述
我需要帮助来设置规则中选项匹配的计数. 此规则示例将匹配(rule2)零次或多次.
I need help setting the count for an option match in a rule. This rule example will match (rule2) zero or more times.
rule1: 'text' ( '(' rule2 ')' )*
我知道+,* 、?计数,但是如果我想让(rule2)匹配5次呢?
I know +,*,? for counts but what if I want the (rule2) to match 5 times?
+,* 、?语法支持的唯一计数修饰符,所以我需要在解析器侦听器中强制计数?
Are +,*,? the only count modifier supported for grammar so I need to enforce count in the parser listener?
推荐答案
我想让(rule2)匹配5次怎么办?
what if I want the (rule2) to match 5 times?
在语法中,有2个选项:
Inside the grammar, there are 2 options:
将其写出5次:
rule1: 'text' '(' rule2 ')' '(' rule2 ')' '(' rule2 ')' '(' rule2 ')' '(' rule2 ')'
2.
或使用语义谓词.请参阅 ANTLR4 Wiki上的使用上下文相关谓词.谓词
2.
or use a semantic predicate. See paragraph Using Context-Dependent Predicates from the ANTLR4 wiki about predicate
+,* 、?语法支持的唯一计数修饰符
Are +,*,? the only count modifier supported for grammar
是的,没有(...){5}
语法可以精确匹配5次.
Yes, there is no (...){5}
syntax to match exactly 5 times.
所以我需要在解析器侦听器中强制计数吗?
so I need to enforce count in the parser listener?
这是(IMO)的最佳选择:在解析器中,只需匹配( '(' rule2 ')' )+
,然后在侦听器/访问者中进行解析后进行验证.
That would be the (IMO) best option: in the parser, just match ( '(' rule2 ')' )+
, and in a listener/visitor validate after parsing.
这篇关于如何在ANTLR中设置规则选项计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!