Java 将表达式解析为AST
参考:https://blog.51cto.com/u_16175468/8063959
https://blog.51cto.com/u_16213690/7305835
import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.tree.*; public class ExpressionParser { public static void main(String[] args) throws Exception { // 创建输入流 InputStream input = new FileInputStream("expression.txt"); // 创建字符流 ANTLRInputStream stream = new ANTLRInputStream(input); // 创建词法分析器 MyLexer lexer = new MyLexer(stream); // 创建Token流 CommonTokenStream tokens = new CommonTokenStream(lexer); // 创建解析器 MyParser parser = new MyParser(tokens); // 开始解析 ParseTree tree = parser.start(); // 打印AST System.out.println(tree.toStringTree()); } }
-------------