你如何将这个正则表达式习语从 Perl 翻译成 Python? [英] How do you translate this regular-expression idiom from Perl into Python?

查看:30
本文介绍了你如何将这个正则表达式习语从 Perl 翻译成 Python?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大约一年前我从 Perl 切换到 Python 并且没有回头.我发现只有 一个 成语在 Perl 中比在 Python 中更容易:

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
}

相应的 Python 代码不是那么优雅,因为 if 语句不断嵌套:

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)

有没有人有一种优雅的方式在 Python 中重现这种模式?我见过使用匿名函数调度表,但对于少数正则表达式,这些表对我来说似乎有点笨拙......

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...

推荐答案

Starting Python 3.8,以及 赋值表达式 (PEP 572)(:= 运算符),我们现在可以捕获条件值 re.search(pattern, text) 在变量 match 中,以便检查它是否不是 None ,然后在条件的主体中重新使用它:

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)

这篇关于你如何将这个正则表达式习语从 Perl 翻译成 Python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆