【问题标题】:Regex phone and email extraction output error - python正则表达式电话和电子邮件提取输出错误 - python
【发布时间】:2024-01-24 07:24:01
【问题描述】:

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

这是我的代码:

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
Missing Miles / AI 的复古信用:airindiaretros.ai@iclployalty.com
Missing Miles / Star Partners 的复古信用:starallianceretros.ai@iclployalty.com
Silver Edge 会员:silveredge.ai@iclployalty.com
Golden Edge 会员:goldenedge.ai@iclployalty.com
大君俱乐部 会员:maharajahclub.ai@iclployalty.com

【问题讨论】:

  • 您能否编辑帖子以包含复制到剪贴板的示例文本?
  • @Matt.G 在这里....实际上我使用了一些随机数据。但这里只是一个电子邮件地址的示例。希望这行得通。

标签: python regex copy paste pyperclip


【解决方案1】:

将 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)

Demo

【讨论】:

    最近更新 更多