從字串內提取電話號碼
阿新 • • 發佈:2018-12-13
直接上程式碼,有問題可以留言
def isPhoneNumber(text): if len(text) != 12: return False for i in range(0, 3): if not text[i].isdecimal(): return False if text[3] != '-': return False for i in range(4, 7): if not text[i].isdecimal(): return False if text[7] != '-': return False for i in range(8, 12): if not text[i].isdecimal(): return False return True
message = 'Call me at 415-555-1011 tomorrow. 415-555-9999 is my office.'
for i in range(len(message)):
chunk = message[i:i + 12]
if isPhoneNumber(chunk):
print(chunk)
print('DONE')
出來的效果:
如果以上方法感覺比較麻煩,我們也可以使用正則來實現。
phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
這個效果大家自己試吧mo = phoneNumRegex.search('My number is 415-555-4242.') print('Phone number found: ' + mo.group())