带有占位符的简单java递归下降解析库
对于应用程序,我想用算术表达式和变量解析字符串。想象一下这个字符串:
((A + B) * C) / (D - (E * F))
所以我这里有占位符,没有实际的整数/双精度值。我正在寻找一个库,它允许我获取第一个占位符,将(例如通过数据库查询)一个值放入占位符中,然后继续处理下一个占位符。
所以我本质上想做的是允许用户在不知道变量的实际值的情况下用他们的域语言编写字符串。因此,应用程序将根据某些“上下文逻辑”提供数值,并输出计算结果。
我用谷歌搜索并没有找到任何合适的库。我找到了 ANTLR,但我认为它对于我的用例来说非常“重量级”。有什么建议吗?
For an application I want to parse a String with arithmetic expressions and variables. Just imagine this string:
((A + B) * C) / (D - (E * F))
So I have placeholders here and no actual integer/double values. I am searching for a library which allows me to get the first placeholder, put (via a database query for example) a value into the placeholder and proceed with the next placeholder.
So what I essentially want to do is to allow users to write a string in their domain language without knowing the actual values of the variables. So the application would provide numeric values depending on some "contextual logic" and would output the result of the calculation.
I googled and did not find any suitable library. I found ANTLR, but I think it would be very "heavyweight" for my usecase. Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你说得对,ANTLR 有点过分了。然而,解析中缀表示法的算术表达式并不难,请参阅:
另外,您还应该考虑使用一些Groovy 或 JRuby 等脚本语言。此外,JDK 6 及以上版本还提供内置 JavaScript 支持。请在此处查看我的答案:使用 Java 创建元语言。
You are right that ANTLR is a bit of an overkill. However parsing arithmetic expressions in infix notation isn't that hard, see:
Also you should consider using some scripting languages like Groovy or JRuby. Also JDK 6 onwards provides built-in JavaScript support. See my answer here: Creating meta language with Java.
如果您只想做简单的表达式,并且您事先知道这些表达式的语法,那么您甚至不需要库;您可以用纯 Java 编写简单的代码。
有关如何操作的详细版本,请参阅此答案:
是否有可在 8 位嵌入式系统上使用的 Flex/bison 替代方案?
如果用户正在定义自己的表达式语言,如果它始终采用一些一元或二元运算符的形式,并且它们可以指定优先级,则可以通过使用多个优先级的运算符列表参数化解析器来改变上述答案。
如果语言可以更复杂,您可能需要研究 元编译器。
If all you want to do is simple expressions, and you know the grammar for those expressions in advance, you don't even need a library; you can code this trivially in pure Java.
See this answer for a detailed version of how:
Is there an alternative for flex/bison that is usable on 8-bit embedded systems?
If the users are defining thier own expression language, if it is always in the form of a few monadic or binary operators, and they can specify the precedence, you can bend the above answer by parameterizing the parser with a list of operators at several levels of precedence.
If the language can be more sophisticated, you might want to investigate metacompilers.