Using re module better

Mike ckimyt at gmail.com
Wed Mar 5 06:32:55 EST 2008


I seem to fall into this trap (maybe my Perl background) where I want
to simultaneously test a regular expression and then extract its match
groups in the same action.  For instance:

if (match = re.search('(\w+)\s*(\w+)', foo)):
    field1 = match.group(1)
    field2 = match.group(2)
    ...

(compare to Perl:)

if($foo =~ /(\w+)\s*(\w+)/) {
    $field1 = $1;
    $field2 = $2;
    ...
}

Problem is, my python is invalid above.  What's the pythonic way to do
this?

Thanks in advance O Python Charmers

Mike



More information about the Python-list mailing list