我需要帮助设置规则中选项匹配的计数。 此规则示例将匹配 (rule2) 零次或多次。
rule1: 'text' ( '(' rule2 ')' )*
我知道+、*、?用于计数,但如果我希望 (rule2) 匹配 5 次怎么办?
是+、*、?语法支持的唯一计数修饰符,因此我需要在解析器监听器中强制计数?
最佳答案
what if I want the (rule2) to match 5 times?
在语法中,有 2 个选项:
1.
写5次:
rule1: 'text' '(' rule2 ')' '(' rule2 ')' '(' rule2 ')' '(' rule2 ')' '(' rule2 ')'
2.
或使用语义谓词。请参阅 ANTLR4 wiki about predicate 中的段落使用上下文相关谓词
Are +,*,? the only count modifier supported for grammar
是的,没有 (...){5}
语法可以精确匹配 5 次。
so I need to enforce count in the parser listener?
这将是(IMO)最佳选择:在解析器中,只需匹配 ( '('rule2 ')' )+
,并在解析后在监听器/访问者中进行验证。
关于antlr - 如何在 ANTLR 中设置规则选项计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25212324/