Grouping and Alternatives


Move the common part in one place and limit the alternation to the part within the parentheses.


examples/regex/alternatives_with_grouping.py
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)

Matched in apple pie
Matched in banana pie