我正在尝试使用正则表达式从网络链接中提取电话号码。我面临的问题是不需要的 id 和网页的其他元素。如果有人可以提出一些改进建议,那将非常有帮助。下面是我在 Python 中使用的代码和正则表达式,
from urllib2 import urlopen as uReq
uClient = uReq(url)
page_html = uClient.read()
print re.findall(r"(\(?\d{3}\D{0,3}\d{3}\D{0,3}\d{4}).*?",page_html)
现在,对于大多数网站,脚本获取一些页面元素值有时是准确的。请建议一些表达上的修改
re.findall(r"(\(?\d{3}\D{0,3}\d{3}\D{0,3}\d{4}).*?",page_html)
对于不同的 url,我的输出如下所示
http://www.fraitagengineering.com/index.html
['(877) 424-4752']
http://hunterhawk.com/
['1481240672', '1481240643', '1479852632', '1478013441', '1481054486', '1481054560', '1481054598', '1481054588', '1476820246', '1481054521', '1481054540', '1476819829', '1481240830', '1479855986', '1479855990', '1479855994', '1479855895', '1476819760', '1476741750', '1476741750', '1476820517', '1479862863', '1476982247', '1481058326', '1481240672', '1481240830', '1513106590', '1481240643', '1479855986', '1479855990', '1479855994', '1479855895', '1479852632', '1478013441', '1715282331', '1041873852', '1736722557', '1525761106', '1481054486', '1476819760', '1481054560', '1476741750', '1481054598', '1476741750', '1481054588', '1476820246', '1481054521', '1476820517', '1479862863', '1481054540', '1476982247', '1476819829', '1481058326', '(925) 798-4950', '2093796260']
http://www.lbjewelrydesign.com/
['213-629-1823', '213-629-1823']
我只想要带有 (000) 000-0000 的电话号码
(不是我在括号后加了空格),
(000)-000-0000或
000-000-0000`格式。任何建议表示赞赏。请注意,我已经提到了这个链接:Find phone numbers in python script
我需要改进正则表达式来满足我的特定需求。
最佳答案
以下正则表达式可用于匹配您提供的样本和其他类似数字:
(\([0-9]{3}\)[\s-]?|[0-9]{3}-)[0-9]{3}-[0-9]{4}
除了使用正则表达式之外,以下示例脚本可用于测试正例和负例:
import re
positiveExamples = [
'(000) 000-0000',
'(000)-000-0000',
'(000)000-0000',
'000-000-0000'
]
negativeExamples = [
'000 000-0000',
'000-000 0000',
'000 000 0000',
'000000-0000',
'000-0000000',
'0000000000'
]
reObj = re.compile(r"(\([0-9]{3}\)[\s-]?|[0-9]{3}-)[0-9]{3}-[0-9]{4}")
for example in positiveExamples:
print 'Asserting positive example: %s' % example
assert reObj.match(example)
for example in negativeExamples:
print 'Asserting negative example: %s' % example
assert reObj.match(example) == None
关于python - 如何改进正则表达式来提取电话号码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47782041/