一文秒懂python正则表达式常用函数

2020-03-07 12:01:24王旭

全搜索:findall/finditer

几乎是最常用的正则表达式函数,用于寻找所有匹配的结果,例如在爬虫信息提取中,可非常方便地提取所有匹配字段

import re
pattern = re.compile(r's[a-z]{2,5}')
text1 = 'this is a re test'
res = pattern.findall(text1)
print(res) #[' is', ' re', ' test']

findall返回的是一个列表对象类型,当无匹配对象时,返回一个空列表。为了避免因同时返回大量匹配结果占用过多内存,可以调用finditer函数返回一个迭代器类型,其中每个迭代元素是一个match对象,可继续调用group和span方法获取相应结果

import re
pattern = re.compile(r's[a-z]{2,5}')
text1 = 'this is a re test'
res = pattern.finditer(text1)
for r in res:
 print(r.group())
"""
 is
 re
 test
"""

当匹配模式串较为简单或者仅需单词调用时,上述所有方法也可直接调用re类函数,而无需事先编译。此时各方法的第一个参数为模式串。

import re
pattern = re.compile(r'd{2,5}')
text = 'this is re test'
re.findall('[a-z]+', text) #['this', 'is', 're', 'test']

03 字符串替换/分割

替换:sub/subn

当需要对文本串进行条件替换时,可调用re.sub实现 (当然也可先编译后再用调用实例方法) ,相应参数分别为模式串、替换格式、文本串,还可以通过增加缺省参数限定替换次数和匹配模式。通过在模式串进行分组,可实现字符串的格式化替换(类似字符串的format方法),以实现特定任务。

import re
text = 'today is 2020-03-05'
print(re.sub('-', '', text)) #'today is 20200305'
print(re.sub('-', '', text, 1)) #'today is 202003-05'
print(re.sub('(d{4})-(d{2})-(d{2})', r'2/3/1', text)) #'today is 03/05/2020'

re.sub的一个变形方法是re.subn,区别是返回一个2元素的元组,其中第一个元素为替换结果,第二个为替换次数

import re
text = 'today is 2020-03-05'
print(re.subn('-', '', text)) #('today is 20200305', 2)

分割:split

还可以调用正则表达式实现字符串的特定分割,相当于.split()方法的一个加强版,实现特定模式的分割,返回一个切割后的结果列表

import re
text = 'today is a re test, what do you mind?'
print(re.split(',', text)) #['today is a re test', ' what do you mind?']

04 总结

python中的re模块提供了正则表达式的常用方法,每种方法都包括类方法调用(如re.match)或模式串的实例调用(pattern.match)2种形式

常用的匹配函数:match/fullmatch 常用的搜索函数:search/findall/finditer 常用的替换函数:sub/subn 常用的切割函数:split 还有其他很多方法,但不是很常用,具体可参考官方文档 另外,python还有第三方正则表达式库regex可供选择