- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下语法:
input
:
formula EOF
;
formula
:
TRUE
| FALSE
| formula AND formula
| formula OR formula
| (quantifier)+ ST condition
;
condition
:
atom EQUALS QUOTE? (assignment | atom) QUOTE?
;
quantifier
:
(FOREACH | EXISTS) variable IN domain
;
.....
它解析简单的一阶逻辑公式。因此,使用以下代码:
String formulaPatternString = "<formula>";
ParseTreePattern formulaPattern = parser.compileParseTreePattern(formulaPatternString, GraphParser.RULE_formula);
List<ParseTreeMatch> formulaMatches = formulaPattern.findAll(tree, "//formula");
我正在查找在我的输入中找到的公式数量。例如
Exists node in GraphA -> node.color='red'
返回一个 formulaMatch
和
Exists node in GraphA -> node.color='red' AND Foreach node in GraphA Exists node1 in GraphB -> node.color=node1.color
返回两个formulaMatches
。现在我想使用 formulaMatches
来结束公式中的量词数量(如您所见,我允许一个或多个)。我认为我需要的方法是 formulaMatches.get(i).getAll("quantifier")
但这会导致 0 个匹配(在我的情况下,第一个公式中的量词部分是 Exists GraphA 中的节点
,第二个是 Foreach 节点 in GraphA Exists node1 in GraphB
这是 2 个量词)。知道如何实现这一目标吗?
最佳答案
formulaMatches
的每个元素将是 ParseTreeMatch
可用于获取 ParseTree
的对象对应<formula>
模式中的占位符。该解析树将是 FormulaContext
。您可以使用 quantifier()
方法FormulaContext
获取 QuantifierContext
的数量它有 child :
for (ParseTreeMatch match : formulaMatches) {
int quantifierCount = ((FormulaContext)match.get("formula")).quantifier().size();
}
注意:如果您使用 ParserInterpreter
进行解析,您的上下文对象将是 InterpreterRuleContext
而不是FormulaContext
。在这种情况下,您需要调用以下命令:
for (ParseTreeMatch match : formulaMatches) {
ParserRuleContext formulaContext = (FormulaContext)match.get("formula");
int quantifierCount = 0;
for (int i = 0; i < formulaContext.getChildCount(); i++) {
if (formulaContext.getChild(i) instanceof RuleNode
&& ((RuleNode)formulaContext.getChild(i)).getRuleContext().getRuleIndex()
== RULE_quantifier)
{
quantifierCount++;
}
}
// quantifierCount is accurate here...
}
关于java - 如何在 ParseTreeMatch ANTLR4 上使用 getAll(...),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22077485/
我有以下语法: input : formula EOF ; formula : TRUE | FALSE | fo
我是一名优秀的程序员,十分优秀!