第七章先通过字符串查找电话号码,比较了是否使用正则表达式程序的差异,明显正则写法更为简洁、易扩展。
模式:3 个数字,一个短横线,3个数字,一个短横线,再是4 个数字。例如:415-555-4242
1 import re 2 ''' 3 不用正则查找模式,匹配3个数字,1个短横线,3个数字,1个短横线,4个数字 4 ex. 111-222-3334 5 ''' 6 7 def isPhoneNo(text): 8 if len(text) != 12: 9 return False 10 for i in range(0,3): 11 if not text[i].isdecimal(): 12 return False 13 if text[3] != '-': 14 return False 15 for i in range(4,7): 16 if not text[i].isdecimal(): 17 return False 18 if text[7] != '-': 19 return False 20 for i in range(8,12): 21 if not text[i].isdecimal(): 22 return False 23 return True 24 25 ''' 26 用正则表达式匹配上述模式 27 ''' 28 def regPhoneNo(text): 29 phoneNoReg=re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') 30 res=phoneNoReg.search(text) 31 if res != None: 32 print('phone No find by reg: '+ res.group()) 33 34 print(isPhoneNo('123-122-9090')) 35 print(isPhoneNo('1234123321')) 36 msg = 'call me at 415-443-1111 tomorrow. 415-443-2222 is my office' 37 for i in range(len(msg)): 38 tmp = msg[i:i+12] 39 if isPhoneNo(tmp): 40 print('phone No find: ' + tmp) 41 regPhoneNo(tmp) 42 print('msg find end')