[Tutor] using regular expressions

Lance E Sloan lsloan@umich.edu
Tue Jul 8 15:41:02 2003


I've converted a program from Perl that processes output from Whois 
servers.  Where the Perl code had read:

  if(/Parent:\s+(\S+)/) {
    [use $1 here]
    ...
  }

I translated it to this Python code:

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

The program's not terribly slow, but I feel bad about the inefficiency of 
using the same regex twice.  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?

--
Lance E Sloan
U-M WATS: Web Applications, Technologies, and Solutions
Full-service web and database design, development, and hosting.
http://websvcs.itd.umich.edu/ - "Putting U on the Web"