Python finds matching patterns
Python Finding Matching Patterns. The above technique of creating multiple condition sets can also be used with regular expressions. Recall that the match()
method or the search()
method of a pattern returns a match object or a None
value. You can exploit this in a program like this:
import re
p1 = re.compile(r”(some) pattern”)
p2 = re.compile(r”a (different) pattern”)
from typing import Optional, Match
def 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
The above defines two patterns and applies them to a given block of text. Each pattern has a subpattern marked with () that acts as a pattern matching group.
The function matcher()
builds a sequence of optional patterns. In this case, it is a set of patterns for simple text pairs. We use a generator expression to apply the search()
method in each pattern to the provided text. Because generator expressions are lazily evaluated, they don’t immediately execute a long series of consecutive pattern matches; instead, they use the results they’ve already obtained.
The filter()
function, with None
as its first argument, removes all None
values from the sequence. filter(None, S)
yields the same value as filter(lambda item: item is not None, S)
.
The next()
function retrieves the first non-empty value from the iterable returned by the filter()
function. If the filter()
function returns no results, it means that no pattern matched. In this case, the exception value is converted to the None
result. Since no pattern matched the given text, it might be wise to raise a custom exception.
As with the previous example, this demonstrates how to evaluate multiple Boolean conditions and select a true value. Because the input is a sequence of patterns, the order in which the different functions are evaluated is well-defined and strictly adhered to. While Python’s strict evaluation order cannot be escaped, the cost of evaluation can be controlled by exiting the function immediately once a matching pattern is found.