perl to python, case + regular expression question

Jim McKim mckim at bandersnatch.lerc.nasa.gov
Tue Jul 25 16:23:10 EDT 2000


I'm looking at adopting python for a project. Until now, most of my
experience has been in perl. Right now I'm cramming python.

I've got a question about what would be a good way in python to
express an operation that needs to be done fairly often in this
project.

The operation (parsing log files) in perl would look like:

if ($input_line =~ /^log entry (\d+)/) {
    my $log_entry_num = $1;
    ...etc.
}
elsif ($input_line =~ /^run number (\d+) timestamp (.*)/) {
    my $run_number = $1;
    my $timestamp = $2;
    ...etc.
}
...

The best way I've been able to come up with in python is to execute a
re.search() method twice, once in the if statement, and then again in
the block following the if statement to obtain the match object.
Something like:

if re.search('^log entry (\d+)', input_line):
    match = re.search('^log entry (\d+)', input_line)
    log_entry_num = match.group(1)
    ...etc.
...

Having to do the search twice looks cluttered and wordy. It probably
isn't efficient. It doesn't enhance maintainability. Is there a better
way?

-- 
Jim McKim
NASA Glenn Research Center




More information about the Python-list mailing list