在ANTLR中,如何指定具体的重复次数?
我使用 ANTLR 指定包含不能超过 254 个字符的行(不包括行结尾)的文件格式。我如何在语法中对其进行编码,缺少这样做:
line : CHAR? CHAR? CHAR? CHAR? ... (254 times)
I'm using ANTLR to specify a file format that contains lines that cannot exceed 254 characters (excluding line endings). How do I encode this in the grammer, short of doing:
line : CHAR? CHAR? CHAR? CHAR? ... (254 times)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这可以通过使用语义谓词来处理。
首先以这样的方式写你的语法,无论你的行有多长。示例如下:
然后将“谓词”添加到
line
规则中:c+=Char
将构造一个包含所有内容的ArrayList
行中的字符。当 ArrayList 的大小超过 5 时,{$c.size()<=5}?
会引发异常。我还在解析器,这样你就可以自己测试它:
它将输出:
HTH
This can be handled by using a semantic predicate.
First write your grammar in such a way that it does not matter how long your lines are. An example would look like this:
and then add the "predicate" to the
line
rule:The
c+=Char
will construct anArrayList
containing all characters in the line. The{$c.size()<=5}?
causes to throw an exception when theArrayList
's size exceeds 5.I also added a main method in the parser so you can test it yourself:
which will output:
HTH