从Python中给定的字符串中提取手机号码

为了轻松解决此问题,我们将在程序中使用re模块。用户将给出一个字符串,我们必须使用Python编程语言提取手机号码。在使用re模块之前,我们将学习有关re模块的一些知识

Python有一个内置的re模块,它使我们能够解决基于模式匹配和字符串操作的各种问题。所述重新模块或正则表达式的正则表达式的简化形式。Python的这个模块在我们的日常生活中非常有用,通过使用re模块,您可以从文件或给定的句子中找到联系电话,电子邮件ID,特殊模式等。re模块提供了许多元字符,为了解决该问题,我们将使用\ d来匹配给定字符串或句子中的任何十进制数字(0-9)。

让我们举个例子来更好地理解问题,

    Input: 
    "Hello! I am bipin Kumar and my contact number is 18912345678. 
    May i know the call logs of my number"    
    Output: 
    18912345678
    Explanation: 
    该程序将必须找到一个包含11位子字符串并打印

解决以上问题的算法

  1. 最初,我们将在程序中导入re模块

  2. 在变量中分配给定的字符串或句子。

  3. 众所周知,联系电话或手机号码为12位数字,这就是为什么我们将形成一种用于提取手机号码的格式。

  4. 现在,打印提取的号码。

程序:

# 导入模块
import re

# 字符串
string='''If you would like to get in touch with us through other ways, 
the Flipkart customer support number is 18002089898. 
And we're just a call away if you need anything. 
You can also arrange a call-back from within the 
Flipkart app regarding any issue related to your order.'''

# 提取手机号码
Phonenumber=re.compile(r'\d\d\d\d\d\d\d\d\d\d\d')
m=Phonenumber.search(string)# 打印结果 
print('从字符串中找到手机号码 : ',m.group())

输出结果

从字符串中找到手机号码:  18002089898