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

  • 来源:新网
  • 更新日期:2018-03-13

摘要: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


t0128cd507c4828bda3.jpg

一、验证邮箱地址:

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(\'someone@gmail.com\') assert email(\'bill.gates@microsoft.com\') assert not email(\'bob#example.com\') assert not email(\'mr-bob@example.com\') 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(\'<Tom Paris> tom@voyager.org\') == \'Tom Paris\' assert name_of_email(\'tom@voyager.org\') == \'tom\' print(\'ok\')