【发布时间】:2019-10-22 04:54:26
【问题描述】:
我尝试编写逻辑来提取给定数据文件中以特定区号(电话号码的前 3 位)开头的电话号码。我的代码是:
import re
data = "This is the sample test data. 2247279133 224dfa7279133 dhana 5107279133 subha 123456789 "
pattern = re.compile(r"((224|510)\d{7})")
matches = pattern.findall(data)
for match in matches:
print (match[0])
我得到的预期输出如下:
2247279133
5107279133
虽然我得到了预期的输出,但我想知道以下几点:
- 这是一种有效的方法吗?
- 是否可以将区号列表作为数组变量而不是硬编码 (
224|510) 传递? - 在 10 GB 的大文件中搜索此类电话号码的推荐方法是什么?
【问题讨论】:
标签: python regex pattern-matching