2019-07-05:正则练习

#encoding=utf-8
"""
1.匹配800-555-1212和555-1212,都可以匹配
"""
import re
s="800-555-1212"
t="555-1212"
def matchDatas(s):
    pattern=re.compile(r'(\d{3}-)?\d{3}-\d{4}')
    match=pattern.match(s).group()
    return match

"""
2.同时可以匹配800-555-1212、555-1212和(800)-555-1212
"""
g="(800)-555-1212"
import re
def matchMulDatas(s):
    partten=re.compile(r"([(]\d{3}[)]-|\d{3}-)?\d{3}-\d{4}")
    match=partten.match(s).group()
    return match


if __name__=="__main__":
    print(matchDatas(s))
    print(matchDatas(t))
    print(matchMulDatas(s))
    print(matchMulDatas(t))
    print(matchMulDatas(g))


 

你可能感兴趣的:(Python)