import re ''' 字符串切割 ''' str1 = "tom is a good man" print(re.split(r' +',str1))#至少一个空格作为切割 ''' re.finditer函数 与findall类似,扫描整个字符串,返回的是一个迭代器next()返回一个对象 ''' str2 = "tom is a good man! tom is a !tom is!" d = re.finditer(r'(tom)',str2) print(next(d))#<re.Match object; span=(0, 3), match='tom'> print(next(d))#<re.Match object; span=(27, 30), match='tom'> print(next(d))#<re.Match object; span=(37, 40), match='tom'> ''' 字符串的替换和修改 re.sub(pattern, repl, string, count=0, flags=0)返回字符串 re.subn(pattern, repl, string, count=0, flags=0)返回元组和修改次数 正则表达式(规则),指定的用来替换的字符串,目标字符串,最多替换次数(默认所有) 先匹配,再替换成指定的字符串 ''' str3 = "tom is a good man" print(re.sub(r'(good)',"nice",str3))#tom is a nice man print(re.subn(r'(good)',"nice",str3))#('tom is a nice man', 1)
正则表达式详解实用-深入
最新推荐文章于 2024-05-18 19:39:33 发布