简体   繁体   English

Python:如何在正则表达式中使用“或”?

[英]Python:How do I use “or” in a regular expression?

I have the text below : 我有以下文字:

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

and I want to use regular expressions to achieve something like below: 而且我想使用正则表达式来实现如下所示:

'apples and oranges' 苹果和橘子

'apples and lemons' 苹果和柠檬

I tried this re.findall('apples and (oranges|lemons)',text) , but it doesn't work. 我尝试了这个re.findall('apples and (oranges|lemons)',text) ,但是它不起作用。

Update: If the 'oranges' and 'lemons' were a list : new_list=['oranges','lemons'] , how could I go to (?:'oranges'|'lemons') without typing them again ? 更新:如果'oranges'和'lemons'是一个列表: new_list=['oranges','lemons'] ,我怎么能不用再次输入而转到(?:'oranges'|'lemons')?

Any ideas? 有任何想法吗? Thanks. 谢谢。

re.findall() : If one or more groups are present in the pattern, return a list of groups; re.findall() :如果模式中存在一个或多个组,则返回组列表;否则,返回一个列表。 this will be a list of tuples if the pattern has more than one group. 如果模式包含多个组,则这将是一个元组列表。

Try this: 尝试这个:

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

(?:...) is a non-capturing version of regular parentheses. (?:...)是常规括号的非捕获版本。

What you've described should work: 您所描述的应该起作用:

In example.py: 在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)

Running python example.py : 运行python example.py

['oranges']
['lemons']
[]

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM