Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #42220

Re: Doing both regex match and assignment within a If loop?

Path csiph.com!usenet.pasdenom.info!news.albasani.net!newsfeed.freenet.ag!news2.euro.net!newsgate.cistron.nl!newsgate.news.xs4all.nl!post.news.xs4all.nl!not-for-mail
Return-Path <chris@rebertia.com>
X-Original-To python-list@python.org
Delivered-To python-list@mail.python.org
X-Spam-Status OK 0.005
X-Spam-Evidence '*H*': 0.99; '*S*': 0.00; 'else:': 0.03; 'elif': 0.05; 'assignment': 0.07; 'lines,': 0.07; 'subject:both': 0.07; 'exception.': 0.09; 'tackle': 0.09; 'cc:addr:python-list': 0.11; 'def': 0.12; 'assume': 0.14; 'etc...': 0.16; 'itself,': 0.16; 'match:': 0.16; 'pythonic': 0.16; 'regex,': 0.16; 'wrote:': 0.18; 'obviously': 0.18; 'trying': 0.19; 'thu,': 0.19; 'import': 0.22; 'cc:addr:python.org': 0.22; 'this?': 0.23; 'cheers,': 0.24; 'cc:2**0': 0.24; 'cc:no real name:2**0': 0.24; 'this:': 0.26; 'second': 0.26; 'certain': 0.27; 'header:In-Reply-To:1': 0.27; 'chris': 0.29; 'raise': 0.29; 'message-id:@mail.gmail.com': 0.30; 'skip:( 20': 0.30; "i'm": 0.30; '"do': 0.31; 'extract': 0.31; 'strip': 0.31; 'option': 0.32; 'could': 0.34; 'something': 0.35; 'test': 0.35; 'but': 0.35; 'received:google.com': 0.35; 'there': 0.35; 'possible': 0.36; 'subject:?': 0.36; 'hi,': 0.36; 'being': 0.38; 'saves': 0.38; 'pm,': 0.38; 'enough': 0.39; 'simple': 0.61; 'further': 0.61; 'choose': 0.64; 'to:addr:gmail.com': 0.65; 'mar': 0.68; 'results': 0.69; 'sender:addr:chris': 0.84; 'victor': 0.84; '\xe2\x80\xa6': 0.84; '9:00': 0.91; 'do:': 0.91; '2013': 0.98
DKIM-Signature v=1; a=rsa-sha256; c=relaxed/relaxed; d=rebertia.com; s=google; h=mime-version:x-received:sender:in-reply-to:references:date :x-google-sender-auth:message-id:subject:from:to:cc:content-type :content-transfer-encoding; bh=5pXAq7c31hzG1XLidTPQnJ0j/kg+omfu5IKOge9vcG0=; b=KUP6elrKUYuP0AQkc/3/iTP4TCOz1L07C0G49rjsPUnXLr3/gvL2ihOP3Y4h0DtcDd HSJ6yyZRvgQ98Z24L9+JBgae5S9B7yPQorz11ijk7dKUPKhX8OXyE9QcY9dQiJkfHSfw Xey+WFNRj3guq2i8SB5hi38EezwVh7wDZT/OY=
X-Google-DKIM-Signature v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20120113; h=mime-version:x-received:sender:in-reply-to:references:date :x-google-sender-auth:message-id:subject:from:to:cc:content-type :content-transfer-encoding:x-gm-message-state; bh=5pXAq7c31hzG1XLidTPQnJ0j/kg+omfu5IKOge9vcG0=; b=MGW2WYlQklWhu/v0RlYBvpkDGuBTfbaA5Z7vmh/NW3szr/Ken64QRN0aK+6YCYCoKX pTzcigV5bW+6t2VLZVZu4HLGhotgnTrG03Uy9ZuYSqVU4m16Y6f1HUNXjN4TdCR62ZxN JwEs/ebaSBb5coLeYbpPdCFniedKi4GYchXSnIzD4+GK7Gok5VHPvPbpdMQW3KpGBTft bfCunSeWXrcWHl9W1+oeWgXB51VJoVN3P23lzMgNxcp7A3GVdqjWrdf93cGRyN9Pk+vb cP2ya/Fl2GMN0jYYckR5oCk1QdPB3q0jyx4Zm9Pwx9LzNnd4NXFOu4v3tJ13h+l/ZeLd SbQQ==
MIME-Version 1.0
X-Received by 10.50.153.165 with SMTP id vh5mr760105igb.48.1364531357535; Thu, 28 Mar 2013 21:29:17 -0700 (PDT)
Sender chris@rebertia.com
In-Reply-To <f8598e49-67af-4a97-98db-9fd69d0182ae@googlegroups.com>
References <f8598e49-67af-4a97-98db-9fd69d0182ae@googlegroups.com>
Date Thu, 28 Mar 2013 21:29:17 -0700
X-Google-Sender-Auth 3etHAQbKSjACMwkkxjIjHw-1MzA
Subject Re: Doing both regex match and assignment within a If loop?
From Chris Rebert <clp2@rebertia.com>
To Victor Hooi <victorhooi@gmail.com>
Content-Type text/plain; charset=UTF-8
Content-Transfer-Encoding quoted-printable
X-Gm-Message-State ALoCoQnIMlgMY6IU100AZLc273V0GA4OObLq70XL1gwPESWMUsxNJev8pKf/mmqZXy2CNsgIJ95p
Cc python-list@python.org
X-BeenThere python-list@python.org
X-Mailman-Version 2.1.15
Precedence list
List-Id General discussion list for the Python programming language <python-list.python.org>
List-Unsubscribe <http://mail.python.org/mailman/options/python-list>, <mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive <http://mail.python.org/pipermail/python-list/>
List-Post <mailto:python-list@python.org>
List-Help <mailto:python-list-request@python.org?subject=help>
List-Subscribe <http://mail.python.org/mailman/listinfo/python-list>, <mailto:python-list-request@python.org?subject=subscribe>
Newsgroups comp.lang.python
Message-ID <mailman.3934.1364531366.2939.python-list@python.org> (permalink)
Lines 87
NNTP-Posting-Host 2001:888:2000:d::a6
X-Trace 1364531366 news.xs4all.nl 6867 [2001:888:2000:d::a6]:33373
X-Complaints-To abuse@xs4all.nl
Xref csiph.com comp.lang.python:42220

Show key headers only | View raw


On Thu, Mar 28, 2013 at 9:00 PM, Victor Hooi <victorhooi@gmail.com> wrote:
> Hi,
>
> I have logline that I need to test against multiple regexes. E.g.:
>
>     import re
>
>     expression1 = re.compile(r'....')
>     expression2 = re.compile(r'....')
>
>     with open('log.txt') as f:
>         for line in f:
>             if expression1.match(line):
>                 # Do something - extract fields from line.
>             elif expression2.match(line):
>                 # Do something else - extract fields from line.
>             else:
>                 # Oh noes! Raise exception.
>
> However, in the "Do something" section - I need access to the match object itself, so that I can strip out certain fields from the line.
>
> Is it possible to somehow test for a match, as well as do assignment of the re match object to a variable?
>
>     if expression1.match(line) = results:
>         results.groupsdict()...

AFAIK, not without hacks and/or being unidiomatic.

> Obviously the above won't work - however, is there a Pythonic way to tackle this?
>
> What I'm trying to avoid is this:
>
>     if expression1.match(line):
>         results = expression1.match(line)
>
> which I assume would call the regex match against the line twice - and when I'm dealing with a huge amount of log lines, slow things down.

def process(line):
    match = expr1.match(line)
    if match:
        # ...extract fields…
        return something
    match = expr2.match(line)
    if match:
        # ...extract fields…
        return something
    # etc…
    raise SomeError()  # Oh noes!

with open('log.txt') as f:
    for line in f:
        results = process(line)


If you choose to further move the extractor snippets into their own
functions, then you can do:


# these could be lambdas if they're simple enough
def case1(match):
    # ...
def case2(match):
    # …
# etc...

REGEX_EXTRACTOR_PAIRS = [
    (re.compile(r'....'), case1),
    (re.compile(r'....'), case2),
    # etc...
]

def process(line):
    for regex, extractor in REGEX_EXTRACTOR_PAIRS:
        match = regex.match(line)
        if match:
            return extractor(match)
    raise SomeError()

Although this second option is likely somewhat less performant, but it
definitely saves on repetition.

Cheers,
Chris

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Doing both regex match and assignment within a If loop? Victor Hooi <victorhooi@gmail.com> - 2013-03-28 21:00 -0700
  Re: Doing both regex match and assignment within a If loop? Chris Rebert <clp2@rebertia.com> - 2013-03-28 21:29 -0700
  Re: Doing both regex match and assignment within a If loop? Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-03-29 06:45 +0000
  Re: Doing both regex match and assignment within a If loop? Peter Otten <__peter__@web.de> - 2013-03-29 09:27 +0100
  Re: Doing both regex match and assignment within a If loop? Alain Ketterlin <alain@dpt-info.u-strasbg.fr> - 2013-03-29 11:06 +0100
    Re: Doing both regex match and assignment within a If loop? Arnaud Delobelle <arnodel@gmail.com> - 2013-03-29 10:41 +0000
    Re: Doing both regex match and assignment within a If loop? Neil Cerutti <neilc@norwich.edu> - 2013-03-29 12:51 +0000
  Re: Doing both regex match and assignment within a If loop? Mitya Sirenef <msirenef@lightbird.net> - 2013-03-29 09:49 -0400

csiph-web