
Why not: from itertools import starmap for x in starmap(re.match, *patterns): if x: break On Tue, Jul 21, 2009 at 8:50 PM, MRAB<python@mrabarnett.plus.com> wrote:
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(). _______________________________________________ Python-ideas mailing list Python-ideas@python.org http://mail.python.org/mailman/listinfo/python-ideas
-- Gerald Britton