zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    MySQL 82 张图带你飞
    Docker一个优秀的应用容器
    大数据架构基础知识
    浏览器复杂吗
    5 分钟学懂 SSH 隧道技术
    图解数据分析如何驱动决策
    3D可视化管理推进能源革命
    一文全面解读B端产品和C端产品的差异
    智慧农业解决方案
    Win10删除右键多余选项菜单
  • 原文地址:https://www.cnblogs.com/sea-stream/p/10181588.html
Copyright © 2011-2022 走看看