首页 > 解决方案 > 正则表达式电话和电子邮件提取输出错误 - python

问题描述

以下程序用于从剪贴板中提取电话号码和电子邮件。问题是每当我复制某些内容并运行此代码时,它都会给出如下所示的输出:

截屏

这是我的代码:

import pyperclip,re
phnRegex=re.compile(r'''(\+\d\d)?       #country code
                        (-|\s|\.)?      #seperator
                            (\d{10})    #numbers
                        ''',re.VERBOSE)

emailRegex=re.compile(r'''[a-zA-Z0-9._+%-]+           #username
                            @
                            [a-zA-Z0-9_-]+              #domain
                            (\.[a-zA-Z]{2,4})           #dot-something
                            ''',re.VERBOSE)
text=str(pyperclip.paste())
matches=[]
for groups in phnRegex.findall(text):
    phoneNum='-'.join(groups[1],groups[3])
    matches.append(phoneNum)
for groups in emailRegex.findall(text):
    matches.append(groups[0])

if len(matches) > 0:
        pyperclip.copy('\n'.join(matches))
        print('Copied to clipboard:')
        print('\n'.join(matches))
else:
    print('No phone numbers or email addresses found.')

任何帮助表示赞赏。

复制的示例文本是:

一般查询:
flyingreturnsbase.ai@iclployalty.com 缺少里程/AI 上的
复古积分:airindiaretros.ai@iclployalty.com 缺少里程/明星合作伙伴的复古积分:starallianceretros.ai@iclployalty.com
银边会员: silveredge.ai@iclployalty .com
Golden Edge 会员:goldenedge.ai@iclployalty.com
大君俱乐部会员:maharajahclub.ai@iclployalty.com

标签: pythonregexcopypastepyperclip

解决方案


将 emailRegex 中的捕获组更改为(?:\.[a-zA-Z]{2,4}) #dot-something

另外,将代码中的 for 循环修改为

for groups in phnRegex.findall(text):
    matches.append(groups[0] + '-' + groups[2])
for groups in emailRegex.findall(text):
    matches.append(groups)

演示


推荐阅读