正则表达式 运用

从剪贴板中查找美国电话号码和电子邮件,并在屏幕打印。

import re
import pyperclip

#为电话创建正则表达式
phoneRegex = re.compile(r'''(
    (\d{3}|\(\d{3}\))?              #区号
    (\s|-|\.)?                      #分隔符
    (\d{3})                         #前三位
    (\s|-|\.)                       #分隔符
    (\d{4})                         #后四位
    (\s*(ext|x|ext.)\s*(\d{2,5}))?  #扩展信息
    )''',re.VERBOSE)

#为E-Mail创建正则表达式
emailRegex = re.compile(r'''(
    [a-zA-Z0-9._%+-]+               #名字
    @                               #@符号
    [a-zA-Z0-9.-]+                  #域名
    (\.[a-zA-Z]{2,4})               #.
    )''',re.VERBOSE)

#在剪贴板文本中找到所有匹配
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])

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

猜你喜欢

转载自www.cnblogs.com/leisurelyRD/p/12355355.html