#! /usr/bin/python3 # =================================================================== # parse a string containing a phone number and return it in # canonical form # =================================================================== # recognized phone number formats are: # (999) 999-9999 # 9999999999 # 999-999-9999 # 999-9999 # 9999999 # # Notes: # 1. extra spaces in the middle are removed # 2. starting and ending spaces are removed # 3. returned canonical form is 999-9999 or 999-999-9999 # # =================================================================== # Definition: # A canonical form means that values can be described or represented # in multiple ways, and one of those ways is chosen as the favored # canonical form. # =================================================================== import re # ---- phone number regular expressions rex2 = [] rex2.append(re.compile(r'^\s*(\d\d\d)-(\d\d\d\d)\s*$')) rex2.append(re.compile(r'^\s*(\d\d\d)(\d\d\d\d)\s*$')) rex3 = [] rex3.append(re.compile(r'^\s*\((\d\d\d)\)\s*(\d\d\d)-(\d\d\d\d)\s*$')) rex3.append(re.compile(r'^\s*(\d\d\d)(\d\d\d)(\d\d\d\d)\s*$')) rex3.append(re.compile(r'^\s*(\d\d\d)-(\d\d\d)-(\d\d\d\d)\s*$')) # ------------------------------------------------------------------- # ----parse Phone Number string # ------------------------------------------------------------------- def ParsePhoneNumber(s): # ---- is there a string to parse? if len(s) < 1: ##print('empty phone number string') return '' # ---- test phone number string # ---- match any of the phone number regrex patterns? ##print(f'Test string = {s}') for p in rex3: m = p.match(s) if m: return f'{m.group(1)}-{m.group(2)}-{m.group(3)}' for p in rex2: m = p.match(s) if m: return f'{m.group(1)}-{m.group(2)}' return '' # ------------------------------------------------------------------- # ---- main # ------------------------------------------------------------------- if __name__ == '__main__': import user_interface as ui if not ui.running_python3(): print('end program - not running Python3') quit() while True: # loop ui.clear_screen() print() s = ui.get_user_input('Enter phone number: ') if not s: # empty string? break pn = ParsePhoneNumber(s) print() if not pn: print('Not a recognized phone number') else: print(f'Phone number is {pn}') ui.pause() print()