The re Module (cont)

Matching Example

     import re
     
     r = re.compile(r'(\d+)\.(\d*)')
     m = r.match("42.37")
     a = m.group(0)        # Returns '42.37'
     b = m.group(1)        # Returns '42'
     c = m.group(2)        # Returns '37'
     print m.start(2)      # Prints 3

A more complex example

     # Replace URL such as http://www.python.org with a hyperlink
     pat = r'(http://[\w-]+(\.[\w-]+)*((/[\w-~]*)?))'
     r = re.compile(pat)
     r.sub('<a href="\\1">\\1</a>',s)     # Replace in string

Where to go from here?

  • Mastering Regular Expressions, by Jeffrey Friedl
  • Online docs
  • Experiment
<<< O'Reilly OSCON 2000, Advanced Python Programming, Slide 30
July 17, 2000, beazley@cs.uchicago.edu
>>>