Best way to extract from regex in if statement

Jon Clements joncle at
Sat Apr 4 03:56:54 CEST 2009

On 4 Apr, 02:14, bwgoudey <bwgou... at> wrote:
> I have a lot of if/elif cases based on regular expressions that I'm using to
> filter stdin and using print to stdout. Often I want to print something
> matched within the regular expression and the moment I've got a lot of cases
> like:
> ...
> elif re.match("^DATASET:\s*(.+) ", line):
>         m=re.match("^DATASET:\s*(.+) ", line)
>         print
> which is ugly because of the duplication but I can't think of a nicer of way
> of doing this that will allow for a lot of these sorts of cases. Any
> suggestions?
> --
> View this message in context:
> Sent from the Python - python-list mailing list archive at

How about something like:

your_regexes = [
    # etc....

for line in lines:
    for rx in your_regexes:
        m = rx.match(line)
        if m:
            break # if only the first matching regex is required,
otherwise leave black for all

Untested, but seems to make sense



More information about the Python-list mailing list