Using re module better

Tim Chase python.list at
Wed Mar 5 13:12:40 CET 2008

> if (match ='(\w+)\s*(\w+)', foo)):

Caveat #1:  use a raw string here
Caveat #2:  inline assignment is verboten

   match ='(\w+)\s*(\w*+)', foo)
   if match:

>     field1 =
>     field2 =

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 =
     if m:
       field1, field2 = m.groups()
       do_something(field1, field2)



More information about the Python-list mailing list