#请尝试写一个验证Email地址的正则表达式。版本一应该可以验证出类似的Email:
#• someone@gmail.com
#• bill.gates@microsoft.com
import re
re_email1=re.compile(r'^[a-zA-Z\][0-9a-zA-Z.]+@[0-9a-zA-Z_]+.com$')
def is_valid_email(addr): if re_email_1.match(addr): return True else: return False
assert is_valid_email('someone@gmail.com') assert is_valid_email('bill.gates@microsoft.com') assert not is_valid_email('bob#example.com') assert not is_valid_email('mr-bob@example.com') print('ok')
#版本二可以提取出带名字的Email地址:
#<Tom Paris> tom@voyager.org => Tom Paris
#bob@example.com => bob
re_email_name = re.compile(r'^[<]?([\w\s]+)[>|@].+$')
def name_of_email(addr): r=re_email_name.match(addr) if r: return r.group(1)
assert name_of_email('<Tom Paris> tom@voyager.org') == 'Tom Paris' assert name_of_email('tom@voyager.org') == 'tom' print('ok')
Sign in to make a reply
何苦来哉ooo
#请尝试写一个验证Email地址的正则表达式。版本一应该可以验证出类似的Email:
#• someone@gmail.com
#• bill.gates@microsoft.com
import re
re_email1=re.compile(r'^[a-zA-Z\][0-9a-zA-Z.]+@[0-9a-zA-Z_]+.com$')
def is_valid_email(addr): if re_email_1.match(addr): return True else: return False
测试:
assert is_valid_email('someone@gmail.com') assert is_valid_email('bill.gates@microsoft.com') assert not is_valid_email('bob#example.com') assert not is_valid_email('mr-bob@example.com') print('ok')
#版本二可以提取出带名字的Email地址:
#<Tom Paris> tom@voyager.org => Tom Paris
#bob@example.com => bob
re_email_name = re.compile(r'^[<]?([\w\s]+)[>|@].+$')
def name_of_email(addr): r=re_email_name.match(addr) if r: return r.group(1)
测试:
assert name_of_email('<Tom Paris> tom@voyager.org') == 'Tom Paris' assert name_of_email('tom@voyager.org') == 'tom' print('ok')