I'm trying to filter a string before passing it through eval
in python. I want to limit it to math functions, but I'm not sure how to strip it with regex. Consider the following:
s = 'math.pi * 8'
I want that to basically translate to 'math.pi*8', stripped of spaces. I also want to strip any letters [A-Za-z]
that are not followed by math\.
.
So if s = 'while(1): print "hello"'
, I want any executable part of it to be stripped:
s would ideally equal something like ():""
in that scenario (all letters gone, because they were not followed by math\.
.
Here's the regex I've tried:
(?<!math\.)[A-Za-z\s]+
and the python:
re.sub(r'(?<!math\.)[A-Za-z\s]+', r'', 'math.pi * 8')
But the result is '.p*8'
, because math.
is not followed by math.
, and i
is not followed by math.
.
How can I strip letters that are not in math
and are not followed by math.
?
What I ended up doing
I followed @Thomas's answer, but also stripped square brackets, spaces, and underscores from the string, in hopes that no python function can be executed other than through the math module:
s = re.sub(r'(\[.*?\]|\s+|_)', '', s)
s = eval(s, {
'__builtins__' : None,
'math' : math
})