Grouping and Alternatives
- ()
Move the common part in one place and limit the alternation to the part within the parentheses.
import re
strings = [
'apple pie',
'banana pie',
'apple'
]
for line in strings:
match = re.search(r'(apple|banana) pie', line)
if match:
print('Matched in', line)
Output:
Matched in apple pie
Matched in banana pie