• 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

  • 相关阅读:
    创建和销毁对象
    echarts折线图堆叠样式 图表只显示一类折线图
    web中跨页面的点击事件
    3DMAX学习笔记——Animate简单的动画
    3DMAX学习笔记——Rendering的时候模型太亮
    Unity3D学习笔记——让Cube沿着某个轴运动
    Unity3D学习笔记——Camera绕着物体旋转
    Unity3D学习笔记——Unity3D的窗口布局
    ZLXSC2015Day1题解
    浅谈同构类问题的骗分算法
  • 原文地址:https://www.cnblogs.com/sea-stream/p/10181588.html
Copyright © 2020-2023  润新知