• python 正则


    match函数

    #!/usr/bin/python3
    import re
    
    line = "Cats are smarter than dogs"
    
    matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)
    
    if matchObj:
       print ("matchObj.group() : ", matchObj.group())
       print ("matchObj.group(1) : ", matchObj.group(1))
       print ("matchObj.group(2) : ", matchObj.group(2))
    else:
       print ("No match!!")

    输出

    matchObj.group() :  Cats are smarter than dogs
    matchObj.group(1) :  Cats
    matchObj.group(2) :  smarter

    search函数

    #!/usr/bin/python3
    import re
    
    line = "Cats are smarter than dogs";
    
    searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I)
    
    if searchObj:
       print ("searchObj.group() : ", searchObj.group())
       print ("searchObj.group(1) : ", searchObj.group(1))
       print ("searchObj.group(2) : ", searchObj.group(2))
    else:
       print ("Nothing found!!")

    输出

    matchObj.group() :  Cats are smarter than dogs
    matchObj.group(1) :  Cats
    matchObj.group(2) :  smarter

    匹配与搜索

    #!/usr/bin/python3
    import re
    
    line = "Cats are smarter than dogs";
    
    matchObj = re.match( r'dogs', line, re.M|re.I)
    if matchObj:
       print ("match --> matchObj.group() : ", matchObj.group())
    else:
       print ("No match!!")
    
    searchObj = re.search( r'dogs', line, re.M|re.I)
    if searchObj:
       print ("search --> searchObj.group() : ", searchObj.group())
    else:
       print ("Nothing found!!")

    输出

    No match!!
    search --> matchObj.group() :  dogs

    搜索和替换

    #!/usr/bin/python3
    import re
    
    phone = "2018-959-559 # This is Phone Number"
    
    # Delete Python-style comments
    num = re.sub(r'#.*$', "", phone)
    print ("Phone Num : ", num)
    
    # Remove anything other than digits
    num = re.sub(r'D', "", phone)    
    print ("Phone Num : ", num)

    输出

    Phone Num :  2018-959-559
    Phone Num :  2018959559

  • 相关阅读:
    python设计模式之命令模式
    [Shell] 生成日期列表
    [Python] Python 获取文件路径
    [Search] 倒排索引与bool检索
    [NLP] Reformer: The Efficient Transformer
    [Alg] 随机抽样完备算法-蓄水池算法 Reservoir Sampling
    [Chaos] 混沌数学学习资料
    [Alg] 文本匹配-多模匹配-WM算法
    [Alg]文本匹配-单模匹配-Sunday算法
    [Alg] 文本匹配-多模匹配-AC自动机
  • 原文地址:https://www.cnblogs.com/sea-stream/p/10181588.html
Copyright © 2020-2023  润新知