[Python-ideas] Proposed convenience functions for re module

Mark Dickinson dickinsm at gmail.com
Wed Jul 22 23:38:11 CEST 2009


On Wed, Jul 22, 2009 at 1:00 AM, Steven D'Aprano<steve at pearwood.info> wrote:
> Following the thread "Experiment: Adding "re" to string objects.", I
> would like to propose the addition of two convenience functions to the
> re module:
>
>
> def multimatch(s, *patterns):
>     """Do a re.match on s using each pattern in patterns,
>     returning the first one to succeed, or None if they all fail."""
>     for pattern in patterns:
>         m = re.match(pattern, s)
>         if m: return m
>
> def multisearch(s, *patterns):
>    """Do a re.search on s using each pattern in patterns,
>    returning the first one to succeed, or None if they all fail."""
>    for pattern in patterns:
>        m = re.search(pattern, s)
>        if m: return m
>
> [...]

Steven, could you show some examples of real(ish)-world use-cases
for one or both of these functions?  Preferably including the code that
might directly follow a multimatch or multisearch call.

It's probably because I haven't used regexes widely enough, but
in all the potential examples I can come up with, either

(1) the regexes are similar enough that they can be refactored into
a single regex (e.g., just concatenated with '|'), or

(2) they're distinct enough that each regex needs its own handing,
so that the multimatch/multisearch would need to be followed by
a multiway 'if/elif/else' anyway;  in this case, it seems that little
is gained.

--
Mark



More information about the Python-ideas mailing list