我有这个程序(Python):
import re
line = "This is a phone number: (061) - 535555. And this is another: 01 - 4657289, 9846012345"
foundNum = re.search(r'((\(?\d{2,3}\)?\D{0,3}\d{6,10})|\d{10})', line)
print("The phone numbers found are: ", foundNum.groups())
我试图从“line”字符串(可能是另一个文本 block )中提取所有电话号码,但它没有给出预期结果,只有一个值(第一个电话号码)重复两次。我错过了什么?
最佳答案
您可以使用 findall
而不是 search
,并且还可以消除嵌套的捕获组:
foundNum = re.findall(r'(\(?\d{2,3}\)?\D{0,3}\d{6,10}|\d{10})', line)
print("The phone numbers found are: ", foundNum)
结果:
('The phone numbers found are: ', ['(061) - 535555', '01 - 4657289', '9846012345'])
re.search()
搜索字符串中第一次出现的 RE 模式,因此它只返回第一个匹配项。表达式re.findall()
以字符串列表的形式返回字符串中模式的所有非重叠匹配项。
关于python - 正则表达式抓取电话号码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44229314/