自动化无聊的东西第7章:正则表达式 - 电话号码和电子邮件提取器仅提取电话号码

xHo*_*dek 6 python

我正在关注这本书,我很确定我会逐字复制代码.当我复制发布商网站(nostarch.com/ContactUs)上的"联系我们"页面并通过该程序运行时,它会输出所有电话号码但没有电子邮件地址.

我确保代码被正确复制.我认为这可能是打印功能的一个问题,所以我尝试将结果粘贴到文本文件中,电子邮件地址仍然无处可寻.

import pyperclip, re

# email regex
emailRegex = re.compile(r'''(
    [a-zA-Z0-9._%+-]+  # username
    @                  # at symbol
    [a-zA-Z0-9.-]+     # domain name
    (\.[a-zA-Z]{2-4})  #dot-something
    )''', re.VERBOSE)

# find matches in clipboard text
text = str(pyperclip.paste())
matches = []
for groups in phoneRegex.findall(text):
    phoneNum = '-'.join([groups[1], groups[3], groups[5]])
    if groups[8] != '':
        phoneNum += ' x' + groups[8]
    matches.append(phoneNum)
for groups in emailRegex.findall(text):
    matches.append(groups[0])

# copy results to the clipboard
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.')
Run Code Online (Sandbox Code Playgroud)

我希望得到结果:

Copied to clipboard:
800-420-7240
415-863-9900
415-863-9950
info@nostarch.com
media@nostarch.com
academic@nostarch.com
help@nostarch.com
Run Code Online (Sandbox Code Playgroud)

但只有这个:

Copied to clipboard:
800-420-7240
415-863-9900
415-863-9950
Run Code Online (Sandbox Code Playgroud)

Poo*_*lka 5

I made sure the code was copied correctly- 不.此时应更换{2-4}{2,4}根据双方正则表达式的语法和第7章的文字看2〜4个字符.

您可以考虑使用https://regex101.com/在线试用正则表达式并查看正则表达式的完整说明.