如何在 ANTLR 中设置规则选项计数 [英] How to set a rule option count in ANTLR

查看:27
本文介绍了如何在 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?

在语法里面,有两个选项:

Inside the grammar, there are 2 options:

写5遍:

rule1: 'text' '(' rule2 ')' '(' rule2 ')' '(' rule2 ')' '(' rule2 ')' '(' rule2 ')'

2.

或使用语义谓词.请参阅 ANTLR4 wiki 中的段落Using Context-Dependent Predicates谓词

是 +,*,?语法支持的唯一计数修饰符

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆