Match groups in Python

Posted by Curd on Stack Overflow See other posts from Stack Overflow or by Curd
Published on 2010-03-31T15:21:06Z Indexed on 2010/03/31 15:23 UTC
Read the original article Hit count: 312

Filed under:
|

Is there a way in Python to access match groups without explicitely creating a match object (or another way to beautify the example below)?

Here is an example to clarify my motivation for the question:

Following perl code

if    ($statement =~ /I love (\w+)/) {
  print "He loves $1\n";
}
elsif ($statement =~ /Ich liebe (\w+)/) {
  print "Er liebt $1\n";
}
elsif ($statement =~ /Je t\'aime (\w+)/) {
  print "Il aime $1\n";
}

translated into Python

m = re.match("I love (\w+)", statement)
if m:
  print "He loves",m.group(1)
else:
  m = re.match("Ich liebe (\w+)", statement)
  if m:
    print "Er liebt",m.group(1)
  else:
    m = re.match("Je t'aime (\w+)", statement)
    if m:
      print "Il aime",m.group(1)

looks very awkward (if-else-cascade, match object creation).

© Stack Overflow or respective owner

Related posts about python

Related posts about regex