[英]Python:How do I use “or” in a regular expression?
我有以下文字:
text='apples and oranges apples and grapes apples and lemons'
而且我想使用正则表达式来实现如下所示:
苹果和橘子
苹果和柠檬
我尝试了这个re.findall('apples and (oranges|lemons)',text)
,但是它不起作用。
更新:如果'oranges'和'lemons'是一个列表: new_list=['oranges','lemons']
,我怎么能不用再次输入而转到(?:'oranges'|'lemons')?
有任何想法吗? 谢谢。
re.findall()
:如果模式中存在一个或多个组,则返回组列表;否则,返回一个列表。 如果模式包含多个组,则这将是一个元组列表。
尝试这个:
re.findall('apples and (?:oranges|lemons)',text)
(?:...)
是常规括号的非捕获版本。
您所描述的应该起作用:
在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']
[]
您是否尝试过非捕获组re.search('apples and (?:oranges|lemons)',text)
吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.