How can I validate a math expression syntax without calculate it [closed]
As long as your expressions follow the Python rules, you can use ast
to validate them:
import ast
expr = '(x + 5) * 3 ?'
try:
ast.parse(expr)
print('valid')
except SyntaxError:
print('invalid')
As correctly pointed out in the comments, since this validates any python code, not only math expressions, you'll need to walk the parsed AST to make sure it doesn't contain things you don't want, like built-in functions.