regular expression: perl ==> python
fredrik at pythonware.com
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 = re.search(r'^(\d+)$', line)
> if m:
> print "int",int(m.group(1))
> m = re.search(r'^(\d*\.\d*)$', line)
> if m:
> print "float",float(m.group(1))
> 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