2016-11-09 55 views
1

我想要構建一個正則表達式來分割'.''[]',但在這裏,我想保留方括號中的結果。正則表達式用方括號和點分割python和re模塊

我的意思是:

import re 
pattern = re.compile("\.|[\[-\]]") 
my_string = "a.b.c[0].d.e[12]" 
pattern.split(my_string) 

# >>> ['a', 'b', 'c', '0', '', 'd', 'e', '12', ''] 

但我希望得到下面的輸出(沒有任何空字符串):

# >>> ['a', 'b', 'c', '0', 'd', 'e', '12'] 

將是這可能嗎?我已經測試了很多正則表達式,這是我找到的最好的,但並不完美。

回答

1

你可以在你的正則表達式和filter使用量詞:

>>> pattern = re.compile(r'[.\[\]]+') 
>>> my_string = "a.b.c[0].d.e[12]" 
>>> filter(None, pattern.split(my_string)) 
['a', 'b', 'c', '0', 'd', 'e', '12'] 
+1

非常感謝!你的regex表達式比我的更好,因爲它解決了我在結果元素之間的空字符串問題 – fenix688