改变 Antlr3 中的词法分析器行为?
NAME: ('a'..'z')+;
QUOTED_NAME: Q NAME Q;
Q: '"';
name : NAME | QUOTED_NAME;
对于 mytext
结果是 mytext
对于 "mytext"
结果是 "mytext"
有什么方法可以考虑Q
词法分析源字符串时,但在请求 QUOTED_NAME
的结果时消除它?所以,我需要的是:
对于 mytext
结果是 mytext
对于 "mytext"
结果是 mytext
< strong>请不要使用内联 Java 解决方案
NAME: ('a'..'z')+;
QUOTED_NAME: Q NAME Q;
Q: '"';
name : NAME | QUOTED_NAME;
for mytext
the result is mytext
for "mytext"
the result is "mytext"
Is there any way to consider Q
when lexing the source string, but eliminate it when QUOTED_NAME
's result is requested? So, what I need is:
for mytext
the result is mytext
for "mytext"
the result is mytext
Please, no inline-Java solutions
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,不添加目标代码(Java 或不同的)就不行。
但我真的不认为有必要:在稍后的阶段,您将处理标记中的文本,为什么不能在该阶段删除引号并将它们留在词法分析阶段?
您可以让解析器创建一个带引号的名称,然后让解析器生成 AST 而不是简单的解析树。使用 AST,您可以告诉解析器要从 AST 中包含哪些标记(以及要删除哪些标记)。然后您可以从树中删除引号。然而,处理引用的文本实际上更多的是属于词法分析器的任务。
不管怎样,这里有一个关于如何创建一个从树中删除引号的 AST 的小演示:
它创建了以下 AST:
输入:有关
使用 ANTLR 创建 AST 的更多信息:如何输出使用 ANTLR 构建的 AST?
No, not without adding target code (Java, or different).
But I don't really see the need: at a later stage you're going to handle the text from your tokens, why can't you remove the quotes at that stage and leave them in there at the lexing-stage?
You could let the parser create a quoted name and then letting the parser produce an AST instead of a simple parse tree. With an AST you can tell the parser which tokens to include (and which to remove) from the AST. You can then remove the quotes from your tree. However, handling quoted text is realy more a task that belongs to the lexer.
Anyway, here's a small demo of how to create an AST that removes the quotes from the tree:
which creates the following AST:
for the input:
More info on creating AST's with ANTLR: How to output the AST built using ANTLR?