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]:
原文地址:https://www.cnblogs.com/zaorunzi/p/9387597.html
时间: 2024-11-03 18:20:41