首页 > 代码库 > python.re模块

python.re模块

#python正则表达式

import re

if __name__=="__main__":
    subPattern= "(([a-zA-Z]+)\.)*"
    subPattern2= "([a-zA-Z]+)"
    pattern= "%s%s@%s%s" % (subPattern, subPattern2, subPattern,subPattern2)
    print(pattern)
    
    mail1="someone@gmail.com"
    mail2="bill.gates@microsoft.com"
    
    rc=re.compile(pattern)
    m1 = rc.match(mail1)
    if m1:
        print("m1=%s" % (m1.groups(),))
        print("m1.group()=%s" % (m1.group(0),))
    
    m2= rc.match(mail2)
    if m2:
        print("m2=%s" % (m2.groups(),))
        print("m2.group()=%s" % (m2.group(0),))
        
        
    mail3="<Tom Paris> tom@voyager.org"
    m3=re.match("^<([a-zA-Z\\s]+)>\\s*[a-zA-Z]+@[a-zA-Z]+\\.[a-zA-Z]+", mail3)
    assert(m3 != None, "match failed!!!")
    print("m3=%s" % (m3.groups(),))
    print("m3.group(0)=%s" % (m3.group(0),))
    print("m3.group(1)=%s" % (m3.group(1),))
    
    """
    #输出结果
    (([a-zA-Z]+)\.)*([a-zA-Z]+)@(([a-zA-Z]+)\.)*([a-zA-Z]+)
    m1=(None, None, 'someone', 'gmail.', 'gmail', 'com')
    m1.group()=someone@gmail.com
    m2=('bill.', 'bill', 'gates', 'microsoft.', 'microsoft', 'com')
    m2.group()=bill.gates@microsoft.com
    m3=('Tom Paris',)
    m3.group(0)=<Tom Paris> tom@voyager.org
    m3.group(1)=Tom Paris
    """

python.re模块