2012-04-13 86 views
0

我有如下文字:Python:如何在正则表达式中使用“或”?

text='apples and oranges apples and grapes apples and lemons' 

,我想用正则表达式来实现类似下面的东西:

“苹果和桔子”

“苹果和柠檬”

我试过这个re.findall('apples and (oranges|lemons)',text),但它不起作用。

更新:如果“桔子”和“柠檬”是一个列表:new_list=['oranges','lemons'],我怎么可能去(:“桔子” |“柠檬”?),而无需再次输入他们?

任何想法?谢谢。

+2

嗯。适用于我。你应该明确你所尝试的内容,以及输出的内容。 – 2012-04-13 00:53:08

回答

6

re.findall():如果模式中存在一个或多个组,则返回组列表;如果模式有多个组,这将是一个元组列表。

试试这个:

re.findall('apples and (?:oranges|lemons)',text) 

(?:...)是常规括号的非捕获版本。

+0

这工作。谢谢。 – GiannisIordanou 2012-04-13 01:09:27

0

您是否尝试过非捕获组re.search('apples and (?:oranges|lemons)',text)

2

你所描述什么应该工作:

在example.py:

import re 
pattern = 'apples and (oranges|lemons)' 
text = "apples and oranges" 
print re.findall(pattern, text) 
text = "apples and lemons" 
print re.findall(pattern, text) 
text = "apples and chainsaws" 
print re.findall(pattern, text) 

运行python example.py

['oranges'] 
['lemons'] 
[] 
相关问题