简体   繁体   中英

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.

Update: If the 'oranges' and 'lemons' were a list : new_list=['oranges','lemons'] , how could I go to (?:'oranges'|'lemons') without typing them again ?

Any ideas? Thanks.

re.findall() : If one or more groups are present in the pattern, return a list of groups; 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:

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 :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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