1 def isPhoneNumber(text): 2 if len(text) != 12: 3 return False 4 for i in range(0, 3): 5 if not text[i].isdecimal(): 6 return False 7 if text[3] != '-': 8 return False 9 for i in range(4, 7): 10 if not text[i].isdecimal(): 11 return False 12 if text[7] != '-': 13 return False 14 for i in range(8, 12): 15 if not text[i].isdecimal(): 16 return False 17 return True 18 19 message = 'Call me at 415-555-1011 tomorrow.415-555-9999 is my office.' 20 for i in range(len(message)): 21 chunk = message[i:i+12] 22 if isPhoneNumber(chunk): 23 print('Phone number fround: ' + chunk) 24 print('Done')
1 C:\PyProjects>C:/Python37/python3.exe c:/PyProjects/isPhoneNumber.py 2 Phone number fround: 415-555-1011 3 Phone number fround: 415-555-9999 4 Done运行结果
1 #!/usr/bin/env python 2 #-*- encoding:utf-8 -*- 3 import re 4 def isPhoneNumber(text): 5 if len(text) != 12: 6 return False 7 for i in range(0, 3): 8 if not text[i].isdecimal(): 9 return False 10 if text[3] != '-': 11 return False 12 for i in range(4, 7): 13 if not text[i].isdecimal(): 14 return False 15 if text[7] != '-': 16 return False 17 for i in range(8, 12): 18 if not text[i].isdecimal(): 19 return False 20 return True 21 22 phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') 23 mo = phoneNumRegex.search('My number is 415-555-4242.') 24 print('Phone number found: ' + mo.group())
1 C:\PyProjects>C:/Python37/python3.exe c:/PyProjects/isPhoneNumber.py 2 Phone number found: 415-555-4242运行结果
Python中使用正则表达式的步骤