我不知道如何在C#中做到這一點,但蟒蛇擁有非常強大的語法樹分析(在AST模塊),可以幫助你在這裏,如果你給你的表情作爲Python表達式(此並不難,你只需要添加'*'乘號:-))。
首先,定義好類,只有重新定義了visit_Name
方法(稱爲標識符,例如另一個visit_Expr
被調用表達式時,一些滿足,visit_Num
叫等,在這裏我們只希望標識符)。
>>> import ast
>>> class MyVisitor(ast.NodeVisitor):
def __init__(self, *args, **kwargs):
super(MyVisitor, self).__init__(*args, **kwargs)
self.identifiers = []
def generic_visit(self, node):
ast.NodeVisitor.generic_visit(self, node)
def visit_Name(self, node):
# You can specify othe exceptions here than cos or sin
if node.id not in ['cos', 'sin']:
self.identifiers.append(node.id)
然後定義一個快速的函數,它的表達給你的標識符:
>>> def visit(expression):
node = ast.parse(expression)
v = MyVisitor()
v.visit(node)
print v.identifiers
它看起來不錯:
>>> visit('x + 4 * sin(t)')
['x', 't']
>>> visit('5*x + 7^sin(z)/2*T + 44')
['x', 'z', 'T']
使用Python 2.6或2.7的AST模塊。
你可以使用ANTLR,看到這個[Q&A] (http://stackoverflow.com/questions/4396080/antlr-3-3-c-tutorials)。 – 2011-04-22 09:07:27
[用於評估數學表達式的最佳算法?]的可能重複(http://stackoverflow.com/questions/572796/best-algorithm-for-evaluating-a-mathematical-expression) – 2011-04-22 10:05:03