[Tutor] using regular expressions

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue Jul 8 15:56:20 2003


On Tue, 8 Jul 2003, Lance E Sloan wrote:

> I tried this Perl-like code, but Python didn't like it:
>
>   if ( ( matches = re.search( r'Parent:\s+(\S+)', line ) ) ):
>     val = matches.group( 1 )
>     [use val here]
>     ...
>
> I get a SyntaxError at the equal-sign.
>
> What's the proper Pythonish way to do this?


Hi Lance,


One way to say it is:

###
    match = re.search( r'Parent:\s+(\S+)', line )
    if match:
        val = match.group( 1 )
    ...
###

This is a line longer than the Perl version.  Python's syntax treats
assignment as a standalone "statement" rather than an "expression", so the
assignment needs to go on a separate line.


If we really want to maintain line count, we can use Alex Martelli's
"Assign and Test" Cookbook recipe:

    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66061


Hope this helps!