有一個字符串,我試圖從符號之間提取值,但符號或分隔符也恰好是字符串的一部分。假設下面的字符串:message =': :1:1st message:2a:2nd message:x:this is where it fails status: fail :3:3rd message'和想要的結果:['1st message','2nd message','this is where it fails status: fail','3rd message']當前代碼和結果:import redef trans(text): text = text+':' tag = re.findall(r':(.*?):',text) return [i for i in tag if not i.isspace()]trans(message)>>['1st message', '2nd message', 'this is where it fails status', '3']知道如何形成我的正則表達式以包含'status: fail '作為結果一部分的模式嗎?
3 回答

四季花海
TA貢獻1811條經驗 獲得超5個贊
您可以使用
re.findall(r'(?<=:\S:).+?(?=\s*:.:|$)', message)
后視冒號內的字符(或字符串的開頭),然后匹配并延遲重復任何字符,直到先行看到冒號內的另一個字符(或字符串的結尾)。
輸出:
['1st message', '2nd message', 'this is where it fails status: fail', '3rd message']
添加回答
舉報
0/150
提交
取消