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

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

问题描述

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

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().想法是向输入的char流询问字符范围.位置值是存储在上下文的开始标记和停止标记中.

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));
}

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

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

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

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