如何获取antlr4规则匹配的原始文本? [英] How do I get the original text that an antlr4 rule matched?

查看:1144
本文介绍了如何获取antlr4规则匹配的原始文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Java 7语法 https://github.com /antlr/grammars-v4/blob/master/java7/Java7.g4 我想找到具有特定名称的方法,然后打印出该方法。我看到匹配时我可以使用 methodDeclaration 规则。所以我子类 Java7BaseListener 并覆盖这个监听器方法:

Using the Java 7 grammar https://github.com/antlr/grammars-v4/blob/master/java7/Java7.g4 I want to find methods with a specific name and then just print out that method. I see that I can use the methodDeclaration rule when I match. So I subclass Java7BaseListener and override this listener method:

@Override public void enterMethodDeclaration(Java7Parser.MethodDeclarationContext ctx) { }

如何获取原始文本? ctx.getText()给我一个字符串,其中删除了所有空格。我想要评论和原始格式。

How do I get the original text out? ctx.getText() gives me a string with all the whitespace stripped out. I want the comments and original formatting.

推荐答案

ANTLR的 CharStream 类有方法 getText(间隔间隔),它将返回给定范围内的原始源。 Context 对象具有获取开头和结尾的方法。假设你的监听器中有一个名为 input 的字段,它正在解析CharStream,你可以这样做:

ANTLR's CharStream class has a method getText(Interval interval) which will return the original source in the give range. The Context object has methods to get the beginning and end. Assuming you have a field in your listener called input which has the CharStream being parsed, you can do this:

    int a = ctx.start.getStartIndex();
    int b = ctx.stop.getStopIndex();
    Interval interval = new Interval(a,b);
    input.getText(interval);

这篇关于如何获取antlr4规则匹配的原始文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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