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

  • 相关阅读:
    python基础代码2
    将博客搬至CSDN
    Python基础代码1
    使用函数处理数据
    创建计算字段
    用通配符进行过滤
    高级过滤数据
    过滤数据
    模式与架构
    工厂方法模式和简单工厂模式的选折
  • 原文地址:https://www.cnblogs.com/sea-stream/p/10181588.html
Copyright © 2011-2022 走看看