''' regex.py Jeff Ondich, 16 Jan 2009 Tianna Avery, November 2018, updated for Python 3 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: https://docs.python.org/3/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(f' "{s}"') print() # Find a simple match regex = 'hog' print(f'Looking for "{regex}".') result = re.search(regex, s) if result: print(f'The first match goes from index {result.start()} to {result.end()-1}') else: print('No match found.') print() # Find a sequence of letters ending in "og". regex = '(\w*og)\W' print(f'Looking for "{regex}".') result = re.search(regex, s) if result: print(f'Found "{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(f'Looking for all occurrences of "{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(f'Splitting the string on all occurrences of "{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(f'Splitting the string on all occurrences of "{regex}".') print(re.sub(regex, 'OGWORD', s)) print()