zoukankan      html  css  js  c++  java
  • re正则表达式公式讲解4

    1.re,split()  字符串分离

    import re
    
    s = "abc20tyu9iou16hij25"
    
    m = re.split("d",s)      #以"d"来进行分割。
    print(m)            # ['abc', '', 'tyu', 'iou', '', 'hij', '', ''] 结果有很多空格,为什么?ans:因为匹配到一个数字就停下来进行分离,第二个数字就变成了空格
    
    m = re.split("d+",s)
    print(m)            # ['abc', 'tyu', 'iou', 'hij', '']结尾还有个空格为什么?因为末尾有个25,25后面没东西,但是25还是要分离一次。
    
    import re
    
    s = "abc20t%yu9iou16#hij25"
    
    
    m = re.split("d+|#|%",s)
    print(m)               # ['abc', 't', 'yu', 'iou', '', 'hij', ''] #iou后面跟着个空格是因为16后面跟这个#,所以就多了个空格。
    

    2.转义字符的用法

    s = "abc20t%yu9|iou16#hij25"
    
    
    # m = re.split("|",s)                # ['abc20t%yu9', 'iou16#hij25']
    # print(m)
    # m = re.split("\\",s)          #分割路径
    # print(m)                                # ['abc20t%yu9|iou16#h', 'ij25']
    

      

    3.re.sub()  替换

    import re
    
    s = "abc20t%yu9|iou16#hij25"
    
    m = re.sub("d+","_",s)
    print(m)                    # abc_t%yu_|iou_#hij_
    
    m = re.sub("d+","_",s,count = 2)       # count = 2 ,前两个替换
    print(m)                    # abc_t%yu_|iou16#hij25 
    

      

    4.maxsplit() 最大分割次数

    import re
    
    s = "1 + 2 -5*3 + 22/2"
    
    m = re.split("[-+*/]",s)           # ['1 ', ' 2 ', '5', '3 ', ' 22', '2']
    print(m)
    
    m = re.split("[-+*/]",s,maxsplit = 3)  # maxsplit 最大分割次数
    print(m)                             # ['1 ', ' 2 ', '5', '3 + 22/2']
    

      

      

      

  • 相关阅读:
    最短路回顾
    树链剖分【模板】
    grep 、find 、tree 新发现
    网口划VLAN
    JDK安装
    网口做trunk
    PXE搭建
    C# 生成DLL文件
    在form窗体里面 寻找当前焦点的控件
    在屏幕右下方显示提示信息(winform窗体)(借鉴)
  • 原文地址:https://www.cnblogs.com/Roc-Atlantis/p/8894174.html
Copyright © 2011-2022 走看看