import re r=re.finditer(r'd+','This is 111 and That is 222') for i in r: print (i.group())
运行结果:

re.split函数
将一个字符串按照正则表达式匹配的子串进行分割后,以列表形式返回。
re.split(pattern, string[, maxsplit=0, flags=0])
pattern:匹配的正则表达式。
string:待匹配的字符串。
maxsplit:分割次数,maxsplit=1分割一次,默认为0,不限次数。
flags:标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等。
import re
r1=re.split('W+','This is 111 and That is 222')
r2=re.split('W+','This is 111 and That is 222',maxsplit=1)
r3=re.split('d+','This is 111 and That is 222')
r4=re.split('d+','This is 111 and That is 222',maxsplit=1)
print(r1)
print(r2)
print(r3)
print(r4)
运行结果:

re.sub函数
re.sub函数用于替换字符串中的匹配项。
re.sub(pattern, repl, string, count=0, flags=0)
pattern:正则中的模式字符串。
repl:替换的字符串,也可为一个函数。
string:要被查找替换的原始字符串。
count:模式匹配后替换的最大次数,默认0表示替换所有的匹配。
import re r='This is 111 and That is 222' # 删除字符串中的数字 r1=re.sub(r'd+','',r) print(r1) # 删除非数字的字符串 r2=re.sub(r'D','',r) print(r2)
运行结果:

参考资料:
https://www.runoob.com/python/python-reg-expressions.html#flags
到此这篇关于Python常用的正则表达式处理函数详解的文章就介绍到这了,更多相关python 正则表达式处理函数内容请搜索易采站长站以前的文章或继续浏览下面的相关文章希望大家以后多多支持易采站长站!









