[英]Regex include the negative lookbehind
我正在嘗試在通過python中的eval
之前過濾字符串。 我想將其限制為數學函數,但是我不確定如何用正則表達式剝離它。 考慮以下:
s = 'math.pi * 8'
我希望基本上將其轉換為'math.pi * 8',並刪除空格。 我也想刪除所有不帶math\\.
字母[A-Za-z]
math\\.
。
因此,如果s = 'while(1): print "hello"'
,我希望剝離其中的任何可執行部分:
理想情況下,s等於():""
類的東西(所有字母都消失了,因為它們后面沒有math\\.
。
這是我嘗試過的正則表達式:
(?<!math\.)[A-Za-z\s]+
和python:
re.sub(r'(?<!math\.)[A-Za-z\s]+', r'', 'math.pi * 8')
但是結果是'.p*8'
,因為math.
后面沒有math.
,而i
沒有math.
。
我如何去除不在math
中且未跟隨math.
字母math.
?
我遵循了@Thomas的回答,但也刪除了字符串中的方括號,空格和下划線,希望除了通過math模塊之外,無法執行任何python函數:
s = re.sub(r'(\[.*?\]|\s+|_)', '', s)
s = eval(s, {
'__builtins__' : None,
'math' : math
})
就像@Carl在評論中說的那樣,請看lybniz可以做什么以取得更好的效果。 但是,這還不夠!
鏈接中描述的技術如下:
print eval(raw_input(), {"__builtins__":None}, {'pi':math.pi})
但這並不能阻止類似
([x for x in 1.0.__class__.__base__.__subclasses__()
if x.__name__ == 'catch_warnings'][0]()
)._module.__builtins__['__import__']('os').system('echo hi!')
來源:Ned Batchelder關於沙箱的幾篇文章,請參見http://nedbatchelder.com/blog/201302/looking_for_python_3_builtins.html
編輯:指出我們沒有方括號或空格,所以:
1.0.__class__.__base__.__subclasses__().__getitem__(i)()._module.__builtins__.get('__import__')('os').system('echo hi')
在這里,您只是為i嘗試了很多價值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.