我需要的只是使用 python 检查字符串是否是有效的数学表达式。
为了简单起见,假设我只需要+ - * /
运算符(+ -
也作为一元)带有数字和嵌套括号。为了完整性,我还添加了简单的变量名称。
所以我可以这样测试:
test("-3 * (2 + 1)") #valid
test("-3 * ") #NOT valid
test("v1 + v2") #valid
test("v2 - 2v") #NOT valid ("2v" not a valid variable name)
I tried py解析 http://pyparsing.wikispaces.com/但只是尝试这个例子:“简单的代数表达式解析器,执行+,-,*,/ and ^算术运算” http://pyparsing.wikispaces.com/file/view/fourFn.py我传递了无效代码并尝试修复它我总是会解析错误的语法而不引发异常
just try:
>>>test('9', 9)
9 qwerty = 9.0 ['9'] => ['9']
>>>test('9 qwerty', 9)
9 qwerty = 9.0 ['9'] => ['9']
两个测试都通过...o_O
有什么建议吗?
This is because the pyparsing code allows functions. (And by the way, it does a lot more than what you need, i.e. create a stack and evaluate that.)
For starters, you could remove pi
and ident
(and possibly something else I'm missing right now) from the code to disallow characters.
原因不同:PyParsing 解析器默认不会尝试消耗整个输入。你必须添加+ StringEnd()
(当然,还要导入它)到末尾expr
如果无法解析整个输入,则使其失败。在这种情况下,pyparsing.ParseException
将被提高。 (来源:http://pyparsing-public.wikispaces.com/FAQ http://pyparsing-public.wikispaces.com/FAQs)
如果您想学习一些解析,那么您需要的内容可能可以使用任何像样的解析库在不到三十行的时间内构建(我喜欢LEPL http://www.acooke.org/lepl/).
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)