python正则表达式之re模块方法介绍
Published on 2018-07-29 20:43 in 分类: Tech / Python with zgxme
分类: Tech / Python

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]: 
    复制代码

     

    posted @   zgxme  阅读(280)  评论(0编辑  收藏  举报
    编辑推荐:
    · AI与.NET技术实操系列(二):开始使用ML.NET
    · 记一次.NET内存居高不下排查解决与启示
    · 探究高空视频全景AR技术的实现原理
    · 理解Rust引用及其生命周期标识(上)
    · 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
    阅读排行:
    · DeepSeek 开源周回顾「GitHub 热点速览」
    · 物流快递公司核心技术能力-地址解析分单基础技术分享
    · .NET 10首个预览版发布:重大改进与新特性概览!
    · AI与.NET技术实操系列(二):开始使用ML.NET
    · 单线程的Redis速度为什么快?
    点击右上角即可分享
    微信分享提示