[Python-ideas] Proposed convenience functions for re module

MRAB python at mrabarnett.plus.com
Wed Jul 22 02:50:34 CEST 2009


Steven D'Aprano 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
> 
> 
> The rationale is to make the following idiom easier:
> 
> 
> m = re.match(s, pattern1)
> if not m:
>     m = re.match(s, pattern2)
>     if not m:
>         m = re.match(s, pattern3)
>         if not m:
>             m = re.match(s, pattern4)
> if m:
>     m.group()
> 
> 
> which will become:
> 
> m = re.multimatch(s, pattern1, pattern2, pattern3, pattern4)
> if m:
>     m.group()
> 
> 
> Is there any support or objections to this proposal? Any comments?
> 
Extend the current re.match and re.search to accept a tuple of patterns:

     m = re.match((pattern1, pattern2, pattern3, pattern4), s)
     if m:
         print m.group()

This format is already used by some string methods, eg str.startswith().



More information about the Python-ideas mailing list