Instead of checking to see if the string contains a valid expression, it might be better to see if it is a valid expression:
whitelist = '^('+'|'.join( # oprators, digits ['-', r'\+', '/', r'\\', r'\*', r'\^', r'\*\*', r'\(', r'\)', '\d+'] # functions of math module (ex. __xxx__) + [f for f in dir(math) if f[:2] != '__']) + ')*$'
The little "r"s are just to make the strings work more correctly, the "^...$" forces it to check the whole string, and the "(...)*" matches an arbitrary string of allowable tokens. Now re.match(whitelist, expr)actually does what was expected above.
Hi,
the following will check the input and make it safe to use. Lets user use all functions in `math` module as well as `natural` expression.
import math
import re
whitelist = '|'.join(
# oprators, digits
['-', '\+', '/', '\\', '\*', '\^', '\*\*', '\(', '\)', '\d+']
# functions of math module (ex. __xxx__)
+ [f for f in dir(math) if f[:2] != '__'])
valid = lambda exp: re.match(whitelist, exp)
>>> valid('23**2')
<_sre.SRE_Match object at 0xb78ac218>
>>> valid('del exp') == None
True
Comment
Instead of checking to see if the string contains a valid expression, it might be better to see if it is a valid expression:
whitelist = '^('+'|'.join(
# oprators, digits
['-', r'\+', '/', r'\\', r'\*', r'\^', r'\*\*', r'\(', r'\)', '\d+']
# functions of math module (ex. __xxx__)
+ [f for f in dir(math) if f[:2] != '__']) + ')*$'
The little "r"s are just to make the strings work more correctly, the "^...$" forces it to check the whole string, and the "(...)*" matches an arbitrary string of allowable tokens. Now re.match(whitelist, expr)actually does what was expected above.
Parent comment
Hi, the following will check the input and make it safe to use. Lets user use all functions in `math` module as well as `natural` expression. import math import re whitelist = '|'.join( # oprators, digits ['-', '\+', '/', '\\', '\*', '\^', '\*\*', '\(', '\)', '\d+'] # functions of math module (ex. __xxx__) + [f for f in dir(math) if f[:2] != '__']) valid = lambda exp: re.match(whitelist, exp) >>> valid('23**2') <_sre.SRE_Match object at 0xb78ac218> >>> valid('del exp') == None True
Replies
Cool! Thanks!