簡體   English   中英

Python:如何在正則表達式中使用“或”?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM