包含python常用函数解释的词条( 三 )


运行结果:
从上面不难发现re.match与re.search的区别:re.match只匹配字符串的起始位置,只要起始位置不符合正则表达式就匹配失败,而re.search是匹配整个字符串,直到找到一个匹配为止 。
re.compile 函数
compile 函数用于编译正则表达式,生成一个正则表达式对象,供 match() 和 search() 这两个函数使用 。
re.compile(pattern[, flags])
pattern:一个字符串形式的正则表达式 。
flags:可选,表示匹配模式,比如忽略大小写,多行模式等 。
import re#匹配数字r=re.compile(r'\d+')r1=r.match('This is a demo')r2=r.match('This is 111 and That is 222',0,27)r3=r.match('This is 111 and That is 222',8,27)print(r1)print(r2)print(r3)
运行结果:
findall函数
搜索字符串,以列表形式返回正则表达式匹配的所有子串,如果没有找到匹配的,则返回空列表 。
需要注意的是,match 和 search 是匹配一次,而findall 匹配所有 。
findall(string[, pos[, endpos]])
string:待匹配的字符串 。
pos:可选参数 , 指定字符串的起始位置 , 默认为0 。
endpos:可选参数,指定字符串的结束位置,默认为字符串的长度 。
import re#匹配数字r=re.compile(r'\d+')r1=r.findall('This is a demo')r2=r.findall('This is 111 and That is 222',0,11)r3=r.findall('This is 111 and That is 222',0,27)print(r1)print(r2)print(r3)
运行结果:
re.finditer函数
和 findall 类似,在字符串中找到正则表达式所匹配的所有子串,并把它们作为一个迭代器返回 。
re.finditer(pattern, string, flags=0)
pattern:匹配的正则表达式 。
string:待匹配的字符串 。
flags:标志位,用于控制正则表达式的匹配方式,如是否区分大小写 , 多行匹配等 。
import rer=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 rer1=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 rer='This is 111 and That is 222'# 删除字符串中的数字r1=re.sub(r'\d+','',r)print(r1)# 删除非数字的字符串r2=re.sub(r'\D','',r)print(r2)
运行结果:
到此这篇关于Python常用的正则表达式处理函数详解的文章就介绍到这了,希望大家以后多多支持!
Python常用函数三有哪些?这7个函数使用频率最高,总算搞明白了1.1 例如:print(hex(2))案例
1.2 输出函数:print(hex(2))
1.3 输出结果:0x2
1.4 解析说明:返回16进制的数 。
2.1 例如:print(chr(10))案例
2.2 输出函数:print(chr(10))
2.3 输出结果:0o12
2.4 解析说明:返回当前整数对应的ASCll码

推荐阅读