晚上好,Stack Overflow。 我想开发一个基于非常简单的上下文无关语法的表达式解释器:
基本上,该语言由 2 个基本语句构成
( SET var 25 ) // Output: var = 25
( GET ( MUL var 5 ) ) // Output: 125
( SET var2 ( MUL 30 5 ) ) //Output: var2 = 150
现在,我很确定我应该做什么来解释一个语句:1) 词法分析将一个语句转换成一个标记序列 2) 语法分析以获得一个符号表(带有变量的 HashMap 和它们的值)和语法树(执行 GET 语句)到 3)执行树的中序访问以获得我想要的结果。
我想要一些关于读取源文件的解析方法的建议。考虑到解析器应该忽略任何空格、制表符或换行符,是否可以使用 Java 模式来获取我要分析的一般语句?有没有一种好方法来阅读像这样格式怪异(并且可能更复杂)的语句
(
SET var
25
)
不会将解析器与左括号和右括号混淆?
例如
Scanner scan; //scanner reading the source file
String pattern = "..." //ideal pattern I've found to represent an expression
while(scan.hasNext(pattern))
Interpreter.computeStatement(scan.next(pattern));
它会是解决这个问题的可行方案吗?
最佳答案
Ira Braxter提出的解决方案:
Your title is extremely confused. You appear to want to parse what are commonly called "S-expressions" in the LISP world; this takes a (simple but) context-free grammar. You cannot parse such expressions with regexps. Time to learn about real parsers.
Maybe this will help: stackoverflow.com/a/2336769/120163
关于java - 基于上下文无关文法解析正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27387166/