builtin regular expressions?

Kay Schluehr kay.schluehr at gmx.net
Sun Oct 1 12:04:58 CEST 2006


Antoine De Groote wrote:
> Hello,
>
> Can anybody tell me the reason(s) why regular expressions are not built
> into Python like it is the case with Ruby and I believe Perl? Like for
> example in the following Ruby code
>
> line = 'some string'
>
> case line
>    when /title=(.*)/
>      puts "Title is #$1"
>    when /track=(.*)/
>      puts "Track is #$1"
>    when /artist=(.*)/
>      puts "Artist is #$1"
> end
>
> I'm sure there are good reasons, but I just don't see them.
>
> Python Culture says: 'Explicit is better than implicit'. May it be
> related to this?
>
> Regards,
> antoine

I notice two issues here. Only one has anything to do with regular
expressions. The other one with 'explicit is better than implicit': the
many implicit passing operations of Rubys case statement. Using
pseudo-Python notation this could be refactored into a more explicit
and not far less concise style:

if line.match( "title=(.*)" ) as m:
   print "Title is %s"%m.group(1)
elif line.match( "track=(.*)" ) as m:
   print "Track is %s"%m.group(1)
elif line.match( "artist=(.*)" ) as m:
   print "Artist is %s"%m.group(1)

Here the result of the test line.match( ) is assigned to the local
variable m if bool(line.match( )) == True. Later m can be used in the
subsequent block. Moreover match becomes a string method. No need for
extra importing re and applying re.compile(). Both can be done in
str.match() if necessary. 

Kay




More information about the Python-list mailing list