Python将字符串与几个正则表达式进行比

mae*_*ics 6 python regex switch-statement

我对Perl和Ruby非常有经验,但对Python很新,所以我希望有人能告诉我Pythonic完成以下任务的方法.我想比较几行与多个正则表达式并检索匹配组.在Ruby中,它将是这样的:

# Revised to show variance in regex and related action.
data, foo, bar = [], nil, nil
input_lines.each do |line|
  if line =~ /Foo(\d+)/
    foo = $1.to_i
  elsif line =~ /Bar=(.*)$/
    bar = $1
  elsif bar
    data.push(line.to_f)
  end
end
Run Code Online (Sandbox Code Playgroud)

我在Python中的尝试变得非常难看,因为匹配组是从正则表达式上的匹配/搜索调用返回的,而Python在条件或switch语句中没有赋值.关于这个问题,Pythonic做什么(或想想!)的方法是什么?

mae*_*ics 0

Paul McGuire 的解决方案是使用中间类REMatcher来执行匹配、存储匹配组并返回成功/失败的布尔值,结果证明为此目的生成了最清晰的代码。