Discuss / Python / 交作业

交作业

Topic source

久疤_796

#1 Created at ... [Delete] [Delete and Lock User]

请尝试写一个验证Email地址的正则表达式。版本一应该可以验证出类似的Email: someone@gmail.com bill.gates@microsoft.com

import re
def fun1(email):
    print(re.match(r'^([0-9a-zA-Z\.\s]+)@(\w+)(\.com|\.org)$',email).groups())
fun1('someone@gmail.com')
fun1('bill.gates@microsoft.com')

版本二可以验证并提取出带名字的Email地址:

<Tom Paris> tom@voyager.org

def fun2(email):
    m = re.match(r'^<([0-9a-zA-Z\.\s]+)>\s+(.+)$',email)
    if m:
        print(m.group(1),end=' ')
        fun1(m.group(2))
    else:
        fun1(email)
fun2('<Tom Paris> tom@voyager.org')
fun2('someone@gmail.com')

久疤_796

#2 Created at ... [Delete] [Delete and Lock User]

个人测试这样写匹配时间通过

s = r'^([0-1][0-9]|2[0-3]|[0-9])\:([0-5][0-9]|[0-9])\:([0-5][0-9]|[0-9])$'
t = '19:21:56'
m = re.match(s,t)
if m:
    print(m.groups())
    print(''.join(x for x in m.groups()))
else:
    print('match failed.')

久疤_796

#3 Created at ... [Delete] [Delete and Lock User]

版本二的话,这样可能好点

def fun2(email):
    m = re.match(r'^<([0-9a-zA-Z\.\s]+)>\s*(.+)$',email)
    if m:
        print(m.group(1),end=' ')
        fun1(m.group(2))
    else:
        fun1(email)
在此插入代码
这样的匹配方式不严谨吧@!
>>> email="<Jiu Ba> NULL"                                        
>>> re.match(r'^<([0-9a-zA-Z\.\s]+)>\s*(.+)$',email)
<_sre.SRE_Match object; span=(0, 13), match='<Jiu Ba> NULL'>

  • 1

Reply