Using re module better

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Wed Mar 5 13:12:51 CET 2008


Mike a écrit :
> I seem to fall into this trap (maybe my Perl background) where I want
> to simultaneously test a regular expression and then extract its match
> groups in the same action.
>  For instance:
> 
> if (match = re.search('(\w+)\s*(\w+)', foo)):
>     field1 = match.group(1)
>     field2 = match.group(2)
>     ...
> 
> (compare to Perl:)
> 
> if($foo =~ /(\w+)\s*(\w+)/) {
>     $field1 = $1;
>     $field2 = $2;
>     ...
> }
> 
> Problem is, my python is invalid above.  What's the pythonic way to do
> this?

In your above use case, the solution is obvious:

match = re.search('(\w+)\s*(\w+)', foo)
if match:
     field1 = match.group(1)
     field2 = match.group(2)


wrt/ assignement as an expression, this has been discussed about 2 days 
ago - look for a thread (badly) named "Is it possible to return a 
variable and use it...?"

HTH



More information about the Python-list mailing list