Discuss / Python / 第二题要用'?'符号

第二题要用'?'符号

Topic source

第一题:

def is_valid_email(addr):
    re_addr=re.compile(r'^[a-z|A-Z|.]+@\w+\.com$')
    if re_addr.match(addr):
        return True
    return None

第二题:

def name_of_email(addr):
    re_addr=re.compile(r'(<([a-z|A-Z|\s]+)>\s)?([a-z]+)@[a-z]+\.[com|org]')
    g=re_addr.match(addr).groups()
    if g[0] or g[1] or g[2] :
        return g[1] or g[2]
    return None

Ye__O

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

第二题,正则表达式末尾增加$,就报错,请指教

re_addr=re.compile(r'^(<([a-z|A-Z|\s]+)>\s)?([a-z]+)@[a-z]+\.[com|org]$')

Ye__O

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

搞明白了,因为^$要求完全匹配

[com|org]这个写法其实不是表示com或org  而是这6个字符中的1个

因为没有完全匹配的约束,实际是部分匹配,所以执行也能成功

可以写成(com|org),虽然group会多一个,但是能够表示com或org的


  • 1

Reply