正则表达式入门

@spiritree  October 9, 2016

正则表达式教程 http://deerchao.net/tutorials/regex/regex.htm

请尝试写一个验证Email地址的正则表达式。版本一应该可以验证出类似的Email:

someone@gmail.com
bill.gates@microsoft.com

import re
emailReg = r'^[a-zA-Z\_][0-9a-zA-Z\_.]*@[\w]+.+[a-zA-Z]+$'
#debug中发现.edu.com的后缀不能匹配,修改'.'为'.+'则可以匹配。
emailStr = r'bill.gates@microsoft.com'
email = re.match(emailReg, emailStr)
if email:
    print('this is an email address')
else:
    print('this is not an email address')

验证并提取出带名字的Email地址:Tom Paris tom@voyager.org

import re
emailReg = r'^<([a-zA-Z]+\s+[a-zA-Z]+)>\s+([0-9a-z\_\.]+@[0-9a-z]+\.[a-z]+)$'
#通过()进行分组
emailStr = r'<Tom Paris> tom@voyager.org'
email = re.match(emailReg, emailStr)
if email:
    print('this is an email address')
    print(email.group(1))
    print(email.group(2))
else:
    print('this is not an email address')

添加新评论