python中的re模块

时间:2022-07-22
本文章向大家介绍python中的re模块,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

如何用Python来进行查询和替换一个文本字符串?

可以使用re模块中的sub()函数或者subn()函数来进行查询和替换, 格式:sub(replacement, string[,count=0])(replacement是被替换成的文本,string是需要被替换的文本,count是一个可选参数,指最大被替换的数量)

>>> import re
>>>p=re.compile(‘blue|white|red’)
>>>print(p.sub(‘colour’,'blue socks and red shoes’))
colour socks and colourshoes
>>>print(p.sub(‘colour’,'blue socks and red shoes’,count=1))
colour socks and redshoes
print(p.subn('colour','blue socks and red shoes'))
('colour socks and colour shoes', 2)
print(p.subn('colour','blue socks and red shoes',count=1))
('colour socks and red shoes', 1)

subn()方法执行的效果跟sub()一样,不过它会返回一个二维数组,包括替换后的新的字符串和总共替换的数量

Python里面match()和search()的区别?

re模块中match(pattern,string[,flags]),检查string的==开头==是否与pattern匹配,这个是全匹配,但是只要是在开头匹配就行。 re模块中re.search(pattern,string[,flags]),在string搜索pattern的第一个匹配值,而且是对当前的字符串的全匹配。

<_sre.SRE_Match object; span=(0, 5), match='super'>
>>>print(re.match(‘super’, ‘superstition’).span())
(0, 5)
>>>print(re.match(‘super’, ‘insuperable’))
None
>>>print(re.search(‘super’, ‘superstition’).span())
(0, 5)
>>>print(re.search(‘super’, ‘insuperable’).span())
(2, 7)
print(re.search('super','msuperstition'))
<_sre.SRE_Match object; span=(1, 6), match='super'>