从字符串内提取电话号码

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38934189/article/details/80662375
直接上代码,有问题可以留言
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())
这个效果大家自己试吧

猜你喜欢

转载自blog.csdn.net/qq_38934189/article/details/80662375