本文介绍了如何获取 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(Interval interval) 将返回原始源给范围.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 规则匹配的原始文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 13:14