context.getText() 排除 ANTLR4 中的空格 [英] context.getText() excludes spaces in ANTLR4

查看:19
本文介绍了context.getText() 排除 ANTLR4 中的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

getText() 返回完整的语句,不包括单词之间的空格.考虑空格的一种方法是将它们包含在语法中.但是,有没有其他方法可以获得包含空格的完整字符串.

The getText() returns the complete statement excluding the spaces between the words. One way of considering the spaces is to include them in grammar. But, is there any other way to get the complete String with the spaces considered.

推荐答案

是的,有(假设你在这里使用的是 ParserRuleContext.getText().这个想法是要求输入字符流一系列字符.位置值存储在上下文的开始和停止标记中.

Yes, there is (assuming here you are using ParserRuleContext.getText(). The idea is to ask the input char stream for a range of characters. The position values are stored in the start and stop tokens of the context.

这是一些代码(从 C++ 转换而来,因此可能不是 100% 正确):

Here's some code (converted from C++, so it might not be 100% correct):

string sourceTextForContext(ParseTree context) {
  Token startToken = (context.start instanceof TerminalNode) ? (TerminalNode)(start).getSymbol() : (ParserRuleContext)(start).start;
  Token stopToken = (context.stop instanceof TerminalNode) ? (TerminalNode)(stop).getSymbol() : (ParserRuleContext)(stop).start;

  CharStream cs = start.getTokenSource().getInputStream();
  int stopIndex = stop != null ? stop.getStopIndex() : -1;
  return cs.getText(new Interval(start.getStartIndex(), stopIndex));
}

由于此检索函数使用绝对字符索引,因此不计入任何可能的空格规则.

Since this retrieval function uses the absolute char indexes, it doesn't count in any possible whitespace rule.

这篇关于context.getText() 排除 ANTLR4 中的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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