正则表达输出的问题
我正在使用以下代码从文本文件中滤除电话号码。
import re
pattern = (r'\d*-\d*-\d*')
names = (r'\w*')
with open('records.txt', 'r') as f:
for line in f:
matches = re.findall(pattern, line)
namesMatch = re.findall(names, line)
if matches:
print(matches)
elif namesMatch:
print(namesMatch + ":")`
我将获得以下输出:
['John']
['222-333-4447']
['423-444-5678']
['123-455-1223']
['Paul']
['423-444-5778']
我想要类似的输出,但以字符串格式如下:
John:
222-333-4447
423-444-5678
123-455-1223
Paul:
423-444-5778
I am using the following code to filter out phone numbers from a text file.
import re
pattern = (r'\d*-\d*-\d*')
names = (r'\w*')
with open('records.txt', 'r') as f:
for line in f:
matches = re.findall(pattern, line)
namesMatch = re.findall(names, line)
if matches:
print(matches)
elif namesMatch:
print(namesMatch + ":")`
I am getting the following output:
['John']
['222-333-4447']
['423-444-5678']
['123-455-1223']
['Paul']
['423-444-5778']
I want a similar output but in string format like below:
John:
222-333-4447
423-444-5678
123-455-1223
Paul:
423-444-5778
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
输出:
请参阅 python demo 。
详细信息:
(\ w+)
- 组1:一个或多个单词chars((?:[\ s:。]*\ d+[ - ] \ d+[ - - ] \ d+)+)+)
- 第1组:以下模式序列发生一个或多个出现[\ s:。]*
- 零或更多whitespaces,colons and dots\ d+
- 一个或多个数字[ - - - ]
- 连字符或dash\ d+[ - - - ] \ d+
- 一个或多个数字,dash,一个或多个数字。You can use
Output:
See the Python demo.
Details:
(\w+)
- Group 1: one or more word chars((?:[\s:.]*\d+[-—–]\d+[-—–]\d+)+)
- Group 1: one or more occurrences of the following pattern sequence[\s:.]*
- zero or more whitespaces, colons and dots\d+
- one or more digits[-—–]
- a hyphen or dash\d+[-—–]\d+
- one or more digits, a dash, one or more digits.