IordanouGiannis
IordanouGiannis

Reputation: 4357

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.

Upvotes: 0

Views: 98

Answers (3)

wjl
wjl

Reputation: 7775

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']
[]

Upvotes: 2

kev
kev

Reputation: 161754

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.

Upvotes: 6

Robbie
Robbie

Reputation: 19500

Have you tried a non-capturing group re.search('apples and (?:oranges|lemons)',text)?

Upvotes: 0

Related Questions