All I need is to check, using python, if a string is a valid math expression or not.
For simplicity let's say I just need + - * /
operators (+ -
as unary too) with numbers and nested parenthesis. I add also simple variable names for completeness.
So I can test this way:
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 pyparsing but just trying the example: "simple algebraic expression parser, that performs +,-,*,/
and ^
arithmetic operations" I get passed invalid code and also trying to fix it I always get wrong syntaxes being parsed without raising Exceptions
just try:
>>>test('9', 9)
9 qwerty = 9.0 ['9'] => ['9']
>>>test('9 qwerty', 9)
9 qwerty = 9.0 ['9'] => ['9']
both test pass... o_O
Any advice?
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 removepi
andident
(and possibly something else I'm missing right now) from the code to disallow characters.The reason is different: PyParsing parsers won't try to consume the whole input by default. You have to add
+ StringEnd()
(and import it, of course) to the end ofexpr
to make it fail if it can't parse the whole input. In that case,pyparsing.ParseException
will be raised. (Source: http://pyparsing-public.wikispaces.com/FAQs)If you care to learn a bit of parsing, what you need can propably be built in less than thirty lines with any decent parsing library (I like LEPL).