'''regex.py Jeff Ondich, 16 Jan 2009 This program gives a brief illustration of a few of the features of the re (regular expression) module. The re module has a lot of complicated and powerful features. You can find the official documentation here: http://docs.python.org/library/re.html ''' import re # We're going to look for stuff inside the following string. s = 'a frog, a dog, and a hog, were agog on the log in the bog' print 'This program will perform regular expression searches on the string:' print ' "%s"' % s print # Find a simple match regex = 'hog' print 'Looking for "%s".' % regex result = re.search(regex, s) if result: print 'The first match goes from index %d to %d' % (result.start(), result.end() - 1) else: print 'No match found.' print # Find a sequence of letters ending in "og". regex = '(\w*og)\W' print 'Looking for "%s".' % regex result = re.search(regex, s) if result: print 'Found "%s"' % result.groups()[0] else: print 'No match found.' print # Find all the sequences of letters ending in "og". regex = '\w*og\\b' # Any guesses why we do \\b instead of \b? print 'Looking for all occurrences of "%s".' % regex result = re.findall(regex, s) if result: print result else: print 'No match found.' print # Split the string on a pattern. regex = '\w*og\\b' print 'Splitting the string on all occurrences of "%s".' % regex result = re.split(regex, s) if result: print result else: print 'No match found.' print # Replace all og-words with OGWORD. regex = '\w*og\\b' print 'Splitting the string on all occurrences of "%s".' % regex print re.sub(regex, 'OGWORD', s) print