python 利用正则表达式 获取邮箱,和电话的函数练习记录

import re


def getEmail(text):
    emailRegex = re.compile(r'([a-zA-Z0-9]{1,64}@[a-zA-Z0-9]{1,64}(.net|.cn|.com.cn|.com|.org|.edu.cn))')
    mos = emailRegex.findall(text)
    list = []
    for x in range(len(mos)):
        list.append(mos[x][0])
    return list


def getPhone(numbers):
    phoneNumRegex = re.compile(r'((\d{3}|\(\d{3}\))-\d{3}-\d{4}(\s{0,5}(ext|x|ext.|\#)\s{0,5}\d{1,10})?)')
    number = phoneNumRegex.findall(text)
    phones = []
    for x in range(len(number)):
        phones.append(number[x][0])
    return phones


text = '''
My email is [email protected],anther email is [email protected], My number is (400)-500-9999 and 499-999-6666 or 499-888-5555 ext.666
My email is [email protected],anther email is [email protected], My number is (400)-500-9999 and 499-999-6666 or 499-888-5555 ext.666
My email is [email protected],anther email is [email protected], My number is (400)-500-9999 and 499-999-6666 or 499-888-5555 ext.666
My email is [email protected],anther email is [email protected], My number is (400)-500-9999 and 499-999-6666 or 499-888-5555 ext.666
My email is [email protected],anther email is [email protected], My number is (400)-500-9999 and 499-999-6666 or 499-888-5555 ext.666
My email is [email protected],anther email is [email protected], My number is (400)-500-9999 and 499-999-6666 or 499-888-5555 ext.666
'''
print(getEmail(text))
print(getPhone(text))

合并处理:

import re, pyperclip


def getEmailAndPhone(text):
    emailRegex = re.compile(r'''([a-zA-Z0-9]{1,64}@[a-zA-Z0-9]{1,64}(.net|.cn|.com.cn|.com|.org|.edu.cn))''')
    phoneNumRegex = re.compile(r'''((\d{3}|\(\d{3}\))-\d{3}-\d{4}(\s{0,5}(ext|x|ext.|\#)\s{0,5}\d{1,10})?)''')
    number = phoneNumRegex.findall(text)
    mos = emailRegex.findall(text)
    list = []
    for x in range(len(mos)):
        list.append(mos[x][0])
    for y in range(len(number)):
        list.append(number[y][0])
    return list


text = '''
My email is [email protected],anther email is [email protected], My number is (400)-500-9999 and 499-999-6666 or 499-888-5555 # 66
'''
matches = getEmailAndPhone(text)
if len(matches) >0:
    pyperclip.copy('\n'.join(matches))
    print('Copied to clipboard:')
    print(pyperclip.paste())
else:
    print('No phone or email!')

输出如下:

Copied to clipboard:
[email protected]
[email protected]
(400)-500-9999
499-999-6666
499-888-5555 # 66

猜你喜欢

转载自blog.csdn.net/tianpingxian/article/details/80298305