我正在使用Python並試圖瞭解如何使用正則表達式。 我有這樣一個字符串列表:從正則表達式中提取字符串Python
example = ['(string1)-(hello)', '(string2)-(world)']
在那裏我有兩個字符串由什麼分隔括號封閉的,所以我只在裏面有什麼感興趣的()。我想獲得一個字符串列表:
example = ['string1', 'hello', 'string2' , 'world']
任何建議如何做到這一點?
我正在使用Python並試圖瞭解如何使用正則表達式。 我有這樣一個字符串列表:從正則表達式中提取字符串Python
example = ['(string1)-(hello)', '(string2)-(world)']
在那裏我有兩個字符串由什麼分隔括號封閉的,所以我只在裏面有什麼感興趣的()。我想獲得一個字符串列表:
example = ['string1', 'hello', 'string2' , 'world']
任何建議如何做到這一點?
使用re.findall
函數以及list_comprehension。
>>> example = ['(string1)-(hello)', '(string2)-(world)']
>>> [x for i in example for x in re.findall(r'\(([^\)]*)\)', i)]
['string1', 'hello', 'string2', 'world']
優秀的緊湊和可讀的工作示例。雖然我會事先執行're.compile',但隨着性能的提高,我發現它更具可讀性。 – MariusSiuram 2015-03-02 09:48:14
@MariusSiuram可讀可能,但是在你給它們定時之前不要聲明性能:Python已經緩存了正則表達式,事實上使用'timeit'我發現'python -m timeit -s「import re」-s「例子= ['(string1) - (hello)','(string2) - (world)']「-s」regex = re.compile(r'\(([^ \)] *)\)')「 「[x for example in for re.findall(regex,i)]」'實際上比'python -m timeit -s「更慢import -s」example = ['(string1) - (hello) ','(string2) - (world)']「」[x for for example in for in in re.findall(r'\(([^ \)] *)\)',i)]'' – Duncan 2015-03-02 10:13:55
I因爲我剛剛完成他們:) – MariusSiuram 2015-03-02 10:27:45
遍歷列表中的每個項目'\(。*?\)'是你正在尋找的東西。 – Maroun 2015-03-02 09:34:31
你也可以看看re的文檔。 [這個例子](https://docs.python.org/2/library/re.html#finding-all-adverbs)可能適合你。 – swenzel 2015-03-02 09:37:39