math syntax checker written in python

前端 未结 3 1331
梦如初夏
梦如初夏 2021-02-15 06:27

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:17

    Why not just evaluate it and catch the syntax error?

    from math import *
    
    def validateSyntax(expression):
      functions = {'__builtins__': None}
      variables = {'__builtins__': None}
    
      functions = {'acos': acos,
                   'asin': asin,
                   'atan': atan,
                   'atan2': atan2,
                   'ceil': ceil,
                   'cos': cos,
                   'cosh': cosh,
                   'degrees': degrees,
                   'exp': exp,
                   'fabs':fabs,
                   'floor': floor,
                   'fmod': fmod,
                   'frexp': frexp,
                   'hypot': hypot,
                   'ldexp': ldexp,
                   'log': log,
                   'log10': log10,
                   'modf': modf,
                   'pow': pow,
                   'radians': radians,
                   'sin': sin,
                   'sinh': sinh,
                   'sqrt': sqrt,
                   'tan': tan,
                   'tanh': tanh}
    
      variables = {'e': e, 'pi': pi}
    
      try:
        eval(expression, variables, functions)
      except (SyntaxError, NameError, ZeroDivisionError):
        return False
      else:
        return True
    

    Here are some samples:

    > print validSyntax('a+b-1') # a, b are undefined, so a NameError arises.
    > False
    
    > print validSyntax('1 + 2')
    > True
    
    > print validSyntax('1 - 2')
    > True
    
    > print validSyntax('1 / 2')
    > True
    
    > print validSyntax('1 * 2')
    > True
    
    > print validSyntax('1 +/ 2')
    > False
    
    > print validSyntax('1 + (2')
    > False
    
    > print validSyntax('import os')
    > False
    
    > print validSyntax('print "asd"')
    > False
    
    > print validSyntax('import os; os.delete("~\test.txt")')
    > False # And the file was not removed
    

    It's restricted to only mathematical operations, so it should work a bit better than a crude eval.

提交回复
热议问题