# # Pattern matching demo program # # Matt Bishop, MHI 289I, Winter 2018 # import re import sys # # loop until end of file # while True: # # read in the pattern # try: pat = raw_input("Pattern: ") except EOFError: break except Exception as msg: print msg continue # # compile the regular expression # try: #pc = re.compile(pat, re.IGNORECASE) pc = re.compile(pat) except Exception as msg: print msg continue # # now loop, matching strings (or not) # while True: # # read in a string # try: print "The pattern is:", pat text = raw_input("Text to match: ") except EOFError: sys.exit(0) except Exception as msg: print msg continue # # now do the matching # print "Does it match the begining of the string? ", m = pc.match(text) if m: print "Yes" print "Here's the string it matched:", m.group() print "Here's the character positions it spans:", m.span() print "Here's the character position where it begins:", m.start() print "Here's the character position where it ends:", m.end() else: print "No" print "Does it match anywhere in the string? ", n = pc.search(text) if n: print "Yes" print "Here's the string it matched:", n.group() print "Here's the character positions it spans:", n.span() print "Here's the character position where it begins:", n.start() print "Here's the character position where it ends:", n.end() else: print "No" print "Here are all the matches: ", print pc.findall(text)