• python正则表达式之re模块方法介绍


    python正则表达式之re模块其他方法

    1:search(pattern,string,flags=0)

    在一个字符串中查找匹配

    2:findall(pattern,string,flags=0)

    找到匹配,返回所有匹配部分的列表

    In [1]: import re
    
    In [2]: str1 = 'imoooc videonum = 1000'
    
    In [3]: str1.find('1000')
    Out[3]: 18
    
    In [4]: info = re.search(r'd+',str1)
    
    In [5]: info
    Out[5]: <_sre.SRE_Match object; span=(18, 22), match='1000'>
    
    In [6]: info.gr
    info.group      info.groupdict  info.groups     
    
    In [6]: info.group()
    Out[6]: '1000'
    
    In [7]: str1 = 'imoooc videonum = 10000'
    
    In [8]: info = re.search(r'd+',str1)
    
    In [9]: info
    Out[9]: <_sre.SRE_Match object; span=(18, 23), match='10000'>
    
    In [10]: info.group()
    Out[10]: '10000'
    
    In [11]: str2 = 'c++=100, java=90, python=80'
    
    In [12]: info = re.search(r'd+',str2)
    
    In [13]: info
    Out[13]: <_sre.SRE_Match object; span=(4, 7), match='100'>
    
    In [14]: info.group()
    Out[14]: '100'
    
    In [15]: info = re.find
    re.findall   re.finditer  
    
    In [15]: info = re.findall(r'd+',str2)
    
    In [16]: info
    Out[16]: ['100', '90', '80']
    
    In [17]: sum([int(x) for x in info])
    Out[17]: 270

    3.sub(pattern,repl,string,count=0,flags=0)

    将字符串中匹配正则表达式的部分替换为其他值

    4.split(pattern,string,maxsplit=0,flags=0)

    根据匹配分割字符串,返回分割字符串组成的列表

    In [22]: str3 = 'imooc videonum = 1000'
    
    In [24]: info = re.sub(r'd+','1001',str3)
    
    In [25]: info
    Out[25]: 'imooc videonum = 1001'
    
    In [26]: def add1(match):
       ....:     val = match.group()
       ....:     num = int(val)+1
       ....:     return str(num)
       ....: 
    
    In [27]: str3
    Out[27]: 'imooc videonum = 1000'
    
    In [28]: re.sub(r'd+',add1,str3)
    Out[28]: 'imooc videonum = 1001'

    In [36]: str4 = 'imooc:C C++ Java Python'
    
    In [37]: re.s
    re.search       re.sre_compile  re.sub          re.sys
    re.split        re.sre_parse    re.subn         
    
    In [37]: re.split(r':| ',str4)
    Out[37]: ['imooc', 'C', 'C++', 'Java', 'Python']
    
    In [38]: re.split(r':| |,',str4)
    Out[38]: ['imooc', 'C', 'C++', 'Java', 'Python']
    
    In [39]: 
  • 相关阅读:
    python笔记-列表和元组
    T-sql for xml path使用(转)
    除非另外还指定了 TOP 或 FOR XML,否则,ORDER BY 子句在视图、内联函数、派生表、子查询和公用表表达式中无效。
    VS2015 经常不出现智能提示,代码颜色也没有了
    虚拟机重新决定网卡地址时,老是报错
    模块的命令
    关闭NetworkManager的作用
    centos6上yum安装drbd(内核:2.6.32.696)
    检查硬件变化的命令kudzu
    parted分区和挂载及非交互式操作
  • 原文地址:https://www.cnblogs.com/zhenggaoxiong/p/9387597.html
Copyright © 2020-2023  润新知