# # Pattern matching demo program # # Matt Bishop, MHI 289I, Fall 2020 # import re import sys # # loop until end of file # while True: # # read in the pattern # try: pat = input("Pattern: ") except EOFError: break 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 = 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? ", end='') m = re.match(pat, 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? ", end='') n = re.search(pat, 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: ", end='') print(re.findall(pat, text))