Finding a matching pattern

This technique of creating a collection of multiple conditions can also be applied when using regular expressions. Recall that a pattern's match() or search() method either returns a match object or None. We can leverage this with programs, as shown in the following code:

import rep1 = re.compile(r"(some) pattern")p2 = re.compile(r"a (different) pattern")from typing import Optional, Matchdef matcher(text: str) -> Optional[Match[str]]:    patterns = [p1, p2]    matching = (p.search(text) for p in patterns)    try:       good = next(filter(None, matching))       return good    except StopIteration:       pass

We've defined two patterns that we'd like to apply against a given block of text. Each pattern has a sub-pattern marked with (), which will ...

Get Functional Python Programming - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.