0

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

4

1 回答 1

2

首先,这不是一个真正的正则表达式问题。

接下来,如果你想在 as3 中使用编译器生成器,请不要使用 flex。使用 ANTLR,它可以针对 AS3 进行输出(无需从 C 移植)。( http://www.antlr.org )

最后,查看中缀到后缀转换的算法。这是关于它的维基百科文章。( http://en.wikipedia.org/wiki/Shunting-yard_algorithm ) 实现起来并不难。

于 2010-03-12T22:01:14.110 回答