[Python-ideas] Proposed convenience functions for re module
Steven D'Aprano
steve at pearwood.info
Wed Jul 22 02:00:52 CEST 2009
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?
--
Steven D'Aprano
More information about the Python-ideas
mailing list