Using re module better
castironpi at gmail.com
castironpi at gmail.com
Wed Mar 5 14:09:28 EST 2008
On Mar 5, 6:12 am, Tim Chase <python.l... at tim.thechases.com> wrote:
> > if (match = re.search('(\w+)\s*(\w+)', foo)):
>
> Caveat #1: use a raw string here
> Caveat #2: inline assignment is verboten
>
> match = re.search(r'(\w+)\s*(\w*+)', foo)
> if match:
>
> > field1 = match.group(1)
> > field2 = match.group(2)
>
> This should then work more or less. However, since you know
> there are two matches, you can just use
>
> field1, field2 = match.groups()
>
> If the regexp is one you plan to reuse (or call in a loop), you
> can pre-compile it:
>
> r = re.compile(r'(\w+)\s*(\w*+)')
> for thing in bunch_of_things:
> m = r.search(thing)
> if m:
> field1, field2 = m.groups()
> do_something(field1, field2)
>
> HTH,
>
> -tkc
Opposed is to mimic MatchGroup that doesn't do anything, and returns
from a non-match call, field1, field2 = match.groups() or [ Dummy,
Dummy ], and similarly ...= [ None, None ].
On another note, why do people X, Y, and Z, including me, all hate to
write a= b(); if a: a.something()?
More information about the Python-list
mailing list