math syntax checker written in python

前端 未结 3 1761
情歌与酒
情歌与酒 2021-02-15 06:53

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 (+ -

3条回答
  •  攒了一身酷
    2021-02-15 07:10

    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.

    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 of expr 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).

提交回复
热议问题