我是靠谱客的博主 坚强春天,这篇文章主要介绍从字符串内提取电话号码,现在分享给大家,希望可以做个参考。

直接上代码,有问题可以留言

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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

 

复制代码
1
message = 'Call me at 415-555-1011 tomorrow. 415-555-9999 is my office.'

 

复制代码
1
2
3
4
5
for i in range(len(message)): chunk = message[i:i + 12] if isPhoneNumber(chunk): print(chunk) print('DONE')

出来的效果:

如果以上方法感觉比较麻烦,我们也可以使用正则来实现。

复制代码
1
phoneNumRegex = re.compile(r'ddd-ddd-dddd')
复制代码
1
2
mo = phoneNumRegex.search('My number is 415-555-4242.') print('Phone number found: ' + mo.group())

这个效果大家自己试吧
 

最后

以上就是坚强春天最近收集整理的关于从字符串内提取电话号码的全部内容,更多相关从字符串内提取电话号码内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(87)

评论列表共有 0 条评论

立即
投稿
返回
顶部