I’m pretty experienced with Perl and Ruby but new to Python so I’m hoping someone can show me the Pythonic way to accomplish the following task. I want to compare several lines against multiple regular expressions and retrieve the matching group. In Ruby it would be something like this:
# 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
My attempts in Python are turning out pretty ugly because the matching group is returned from a call to match/search on a regular expression and Python has no assignment in conditionals or switch statements. What’s the Pythonic way to do (or think!) about this problem?
Paul McGuire’s solution of using an intermediate class
REMatcherwhich performs the match, stores the match group, and returns a boolean for success/fail turned out to produce the most legible code for this purpose.