perl to python, case + regular expression question

Bjorn Pettersen bjorn at roguewave.com
Tue Jul 25 17:03:47 EDT 2000


Jim McKim wrote:
> 

[snip]

> 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.
> ...

The canonical way is:

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

you might also want to take a look at re.compile() if you are matching a
lot of regular expressions frequently (I believe the current
implementation caches ~30, but I haven't looked at the code lately...)

at-least-until-someone-starts-arguing-for-assignment-expressions-again'ly
y'rs
-- bjorn




More information about the Python-list mailing list