从正则表达式中提取字符串Python

问题描述:

我正在使用Python并试图了解如何使用正则表达式。 我有这样一个字符串列表:从正则表达式中提取字符串Python

example = ['(string1)-(hello)', '(string2)-(world)'] 

在那里我有两个字符串由什么分隔括号封闭的,所以我只在里面有什么感兴趣的()。我想获得一个字符串列表:

example = ['string1', 'hello', 'string2' , 'world'] 

任何建议如何做到这一点?

+1

遍历列表中的每个项目'\(。*?\)'是你正在寻找的东西。 – Maroun 2015-03-02 09:34:31

+0

你也可以看看re的文档。 [这个例子](https://docs.python.org/2/library/re.html#finding-all-adverbs)可能适合你。 – swenzel 2015-03-02 09:37:39

使用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'] 
+2

优秀的紧凑和可读的工作示例。虽然我会事先执行're.compile',但随着性能的提高,我发现它更具可读性。 – MariusSiuram 2015-03-02 09:48:14

+0

@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

+0

I因为我刚刚完成他们:) – MariusSiuram 2015-03-02 10:27:45