Python comparing string against several regular expressions
Posted
by maerics
on Stack Overflow
See other posts from Stack Overflow
or by maerics
Published on 2010-04-13T22:51:42Z
Indexed on
2010/04/13
22:53 UTC
Read the original article
Hit count: 276
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:
STDIN.each_line do |line|
case line
when /^A:(.*?)$/ then puts "FOO: #{$1}"
when /^B:(.*?)$/ then puts "BAR: #{$1}"
# when ...
else puts "NO MATCH: #{line}"
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?
© Stack Overflow or respective owner