regular expression: perl ==> python

Fredrik Lundh fredrik at
Wed Dec 22 20:08:07 CET 2004

Nick Craig-Wood wrote:

> I've found that a slight irritation in python compared to perl - the
> fact that you need to create a match object (rather than relying on
> the silver thread of $_ (etc) running through your program ;-)

the old "regex" engine associated the match with the pattern, but that
approach isn't thread safe...

> line = "123123"
> m ='^(\d+)$', line)
> if m:
>   print "int",int(
> else:
>   m ='^(\d*\.\d*)$', line)
>   if m:
>      print "float",float(
>   else:
>      print "unknown thing", line

that's not a very efficient way to match multiple patterns, though.  a
much better way is to combine the patterns into a single one, and use
the "lastindex" attribute to figure out which one that matched.  see

for more on this topic.


More information about the Python-list mailing list