Note that there are some explanatory texts on larger screens.

plurals
  1. PORegex include the negative lookbehind
    primarykey
    data
    text
    <p>I'm trying to filter a string before passing it through <code>eval</code> in python. I want to limit it to math functions, but I'm not sure how to strip it with regex. Consider the following:</p> <pre><code>s = 'math.pi * 8' </code></pre> <p>I want that to basically translate to 'math.pi*8', stripped of spaces. I also want to strip any letters <code>[A-Za-z]</code> that are not followed by <code>math\.</code>.</p> <p>So if <code>s = 'while(1): print "hello"'</code>, I want any executable part of it to be stripped:</p> <p>s would ideally equal something like <code>():""</code> in that scenario (all letters gone, because they were not followed by <code>math\.</code>.</p> <p>Here's the regex I've tried:</p> <pre><code>(?&lt;!math\.)[A-Za-z\s]+ </code></pre> <p>and the python:</p> <pre><code>re.sub(r'(?&lt;!math\.)[A-Za-z\s]+', r'', 'math.pi * 8') </code></pre> <p>But the result is <code>'.p*8'</code>, because <code>math.</code> is not followed by <code>math.</code>, and <code>i</code> is not followed by <code>math.</code>.</p> <p>How can I strip letters that are not in <code>math</code> and are not followed by <code>math.</code>?</p> <h2>What I ended up doing</h2> <p>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:</p> <pre><code>s = re.sub(r'(\[.*?\]|\s+|_)', '', s) s = eval(s, { '__builtins__' : None, 'math' : math }) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload