Doing both regex match and assignment within a If loop?
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Fri Mar 29 02:45:37 EDT 2013
On Thu, 28 Mar 2013 21:00:44 -0700, Victor Hooi wrote:
> Is it possible to somehow test for a match, as well as do assignment of
> the re match object to a variable?
mo = expression.match(line)
if mo:
...
Many problems become trivial when we stop trying to fit everything into a
single line :-)
> if expression1.match(line) = results:
> results.groupsdict()...
>
> Obviously the above won't work - however, is there a Pythonic way to
> tackle this?
Yes. Stop trying to fit everything into a single line :-)
I would approach the problem like this:
LOOKUP_TABLE = {expression1: do_something,
expression2: do_something_else,
expression3: function3,
expression4: function4, # etc.
}
with open('log.txt') as f:
for line in f:
for expr, func in LOOKUP_TABLE.items():
mo = expr.match(line)
if mo:
func(line, mo)
break
else:
# If we get here, we never reached the break.
raise SomeException
If you don't like having that many top level functions, you could make
them methods of a class.
If you only have two or three expressions to test, and the body of each
if clause is small, it's probably too much effort to write functions for
each one. In that case, I'd stick to the slightly more verbose form:
with open('log.txt') as f:
for line in f:
mo = expression1.match(line)
if mo:
do_this()
do_that()
mo = expression2.match(line)
if mo:
do_something_else()
mo = expression3.match(line)
if mo:
fe()
fi()
fo()
fum()
else:
raise SomeException
> 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
Correct.
--
Steven
More information about the Python-list
mailing list