regular expression: perl ==> python

Fredrik Lundh fredrik at pythonware.com
Wed Dec 22 14:08:07 EST 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 = re.search(r'^(\d+)$', line)
> if m:
>   print "int",int(m.group(1))
> else:
>   m = re.search(r'^(\d*\.\d*)$', line)
>   if m:
>      print "float",float(m.group(1))
>   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

    http://effbot.org/zone/xml-scanner.htm

for more on this topic.

</F> 






More information about the Python-list mailing list