ActionScript 中具有嵌套和变量的计算表达式解析器
我试图在我的地图应用程序的配置文件中启用动态字段,但我无法弄清楚如何解析用户传入的“方程”,至少不能从头开始编写整个解析器!我确信有一些更简单的方法可以做到这一点,所以我正在寻求想法!
基本思想:
public var testString:String = "(#TOTPOP_CY#-#HISPOP_CY#)/#TOTPOP_CY#";
public var valueObject:Object = {TOTPOP_CY:1000, HISPOP_CY:100};
public function calcParse(eq:String):String {
// do calculations
return calculatedValue
}
到目前为止,我正在考虑通过运算符或变量标记来拆分表达式,但这消除了括号嵌套。或者,使用一系列正则表达式来搜索表达式的每个部分并将其替换为其值,递归运行直到只剩下一个数字。但我不认为正则表达式会做数学(即用两个数字的总和替换“\d + \d”) 理想情况下,我只是用它们的值查找/替换所有变量名,然后运行 eval(),但是 AS 中没有 eval...
eesh
我下载了一些编译器设计课程的课程材料,所以也许我'只需编写一个成熟的计算器语言和解析器,并将其从 OTHER flex 移植过来(解析器生成器):-D
I'm trying to enable dynamic fields in the configuration file for my mapping app, but I can't figure out how to parse the "equation" passed in by the user, at least not without writing a whole parser from scratch! I'm sure there is some easier way to do this, and so I'm asking for ideas!
Basic idea:
public var testString:String = "(#TOTPOP_CY#-#HISPOP_CY#)/#TOTPOP_CY#";
public var valueObject:Object = {TOTPOP_CY:1000, HISPOP_CY:100};
public function calcParse(eq:String):String {
// do calculations
return calculatedValue
}
So far, I was thinking of splitting the expression by either the operators, or maybe the variable tokens, but that gets rid of the parenthetical nesting. Alternatively, use a series of regex to search and replace each piece of the expression with its value, recursively running until only a number is left. But I don't think regex does math (i.e. replace "\d + \d" with the sum of the two numbers)
Ideally, I'd just do a find/replace all variable names with their values, then run an eval(), but there's no eval in AS...
eesh
I downloaded some course materials for a course on compiler design, so maybe I'll just write a full-fledged calculator language and parser and port it over from the OTHER flex (the parser generator) :-D
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,这并不是一个真正的正则表达式问题。
接下来,如果你想在as3中使用编译器生成器,就不要使用flex。使用ANTLR,它可以针对AS3进行输出(无需从C移植)。 (http://www.antlr.org)
最后,查看中缀到后缀转换的算法。这是关于它的维基百科文章。 (http://en.wikipedia.org/wiki/Shunting-yard_algorithm)
实施起来并不太难。
First things first, this isn't really a regex problem.
Next, if you want to use a compiler generator in as3, don't use flex. Use ANTLR, it can target AS3 for output (no need to port it from C). (http://www.antlr.org)
Finally, check out the algorithms for infix to postfix conversion. Here's the wikipedia article on it. (http://en.wikipedia.org/wiki/Shunting-yard_algorithm)
It's not too tough to implement.