(1)新建一个Java工程
(2)创建文件夹【lib】,把【antlr-4.9.2-complete.jar】拷贝到【lib】下面:
(3)【antlr-4.9.2-complete.jar】上点右键 ->【Build Path】->【Add to Build Path】
jar关联上了:
(4)修改ANTLR Tool version 4.4支持的jar版本,否则之后运行时会报错。
参考:https://blog.csdn.net/weixin_50552284/article/details/115721309
(5)把g4文件编译生成的4个java文件和2个tokens文件拷贝到当前工程:
(6)文件头上加上package语句:
(7)编写Main.java:
package abc;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.ParseTree;
public class Main {
public static void main(String[] args) throws Exception {
CharStream antlrInput = CharStreams.fromFileName("D:\\input.txt");
test02Lexer lexer = new test02Lexer(antlrInput);
CommonTokenStream tokens = new CommonTokenStream(lexer);
test02Parser parser = new test02Parser(tokens);
ParseTree tree = parser.file();
String output = tree.toStringTree(parser);
System.out.print(output);
}
}
(8)准备好文件:D:\input.txt
文件内容:
ABC;
(9)编译工程,执行。控制台输出文法识别的结果,说明OK了。
【完】