2016-10-16 81 views
0

我想在Python中使用正則表達式模式分割字符串,但它不能正常工作。試圖與正則表達式分割字符串

實施例文本:

"The quick {brown fox} jumped over the {lazy} dog"

代碼:

"The quick {brown fox} jumped over the {lazy} dog".split(r'({.*?}))

我使用捕獲組使得分割分隔符被保留在數組中。

期望的結果:

['The quick', '{brown fox}', 'jumped over the', '{lazy}', 'dog']

實際結果:

['The quick {brown fox} jumped over the {lazy} dog']

正如你可以看到有明顯不匹配,因爲它沒有拆分字符串。任何人都可以讓我知道我要去哪裏嗎?謝謝。

回答

1

你調用字符串分裂法,不重的

>>> re.split(r'({.*?})', "The quick {brown fox} jumped over the {lazy} dog") 
['The quick ', '{brown fox}', ' jumped over the ', '{lazy}', ' dog']