How do you translate this regular-expression idiom from Perl into Python?

perl, python, regex

Solution

Starting `Python 3.8`, and the introduction of assignment expressions (PEP 572) (`:=` operator), we can now capture the condition value `re.search(pattern, text)` in a variable `match` in order to both check if it's not `None` and then re-use it within the body of the condition:

if match := re.search(r'foo(.+)', text):
  # do something with match.group(1)
elif match := re.search(r'bar(.+)', text):
  # do something with match.group(1)
elif match := re.search(r'baz(.+)', text)
  # do something with match.group(1)

Problem

I switched from Perl to Python about a year ago and haven't looked back. There is only one idiom that I've ever found I can do more easily in Perl than in Python: ``` if ($var =~ /foo(.+)/) { # do something with $1 } elsif ($var =~ /bar(.+)/) { # do something with $1 } elsif ($var =~ /baz(.+)/) { # do something with $1 } ``` The corresponding Python code is not so elegant since the if statements keep getting nested: ``` m = re.search(r'foo(.+)', var) if m: # do something with m.group(1) else: m = re.search(r'bar(.+)', var) if m: # do something with m.group(1) else: m = re.search(r'baz(.+)', var) if m: # do something with m.group(2) ``` Does anyone have an elegant way to reproduce this pattern in Python? I've seen anonymous function dispatch tables used, but those seem kind of unwieldy to me for a small number of regular expressions...

Original source

Related problems