Python 正则表达式 关于邮箱地址

Python 正则表达式 验证邮箱地址以及取出邮箱主人名字
来源于某博客某篇文章下某大神的作业
特此感谢@手机用户2935462955

一、验证邮箱地址:

import re 

def email(addr):
    email = re.compile(r'^([\w|d]*\.?[\w|d]*)@([\w|d]*)(.com|.cn|.net|.org)$')
    if email.match(addr):
        return True
    else:
        return False

# 测试:
assert email('[email protected]')
assert email('[email protected]')
assert not email('bob#example.com')
assert not email('[email protected]')
print('ok')

match = r’^([\w|d].?[\w|d])@([\w|d]*)(.com|.cn|.net|.org)$’

可以判断常见邮箱格式

二、取出邮箱主人名字:

import re

def name_of_email(addr):
    re_name_of_email = re.compile(r'^\<([\w|\d]*\s?[\w|\d]*)\>\s+|([\w|\d]*\.?[\w|\d]*)@([\w|\d]*)(.com|.cn|.net|.org)$')
    if re_name_of_email.match(addr).group(1):
        return re_name_of_email.match(addr).group(1)
    else:
        return re_name_of_email.match(addr).group(2)

# 测试:
assert name_of_email(' [email protected]') == 'Tom Paris'
assert name_of_email('[email protected]') == 'tom'
print('ok')

你可能感兴趣的:(python-学习之路)