Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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