python函数方法 python函数方法命名规范( 六 )


import repattern = re.compile(r'[a-z]{2,5}')type(pattern) #re.Pattern
此例创建了一个正则表达式式对象 (re.pattern)  , 命名为pattern,用于匹配2-5位小写字母的模式串 。后续在使用其他正则表达式函数时 , 即可使用pattern进行方法调用 。
匹配:match
match函数用于从文本串的起始位置开始匹配,若匹配成功 , 则返回相应的匹配对象,此时可调用group()方法返回匹配结果,也可用span()方法返回匹配起止下标区间;否则返回None
import repattern = re.compile(r'[a-z]{2,5}')text1 = 'this is a re test'res = pattern.match(text1)print(res) #if res:print(res.group()) #thisprint(res.span()) #(0, 4)text2 = '是的, this is a re test'print(pattern.match(text2))#None
match函数还有一个变形函数fullmatch,当且仅当模式串与文本串刚好全部匹配时,返回一个匹配对象,否则返回None
搜索:search
match只提供了从文本串起始位置匹配的结果 , 如果想从任意位置匹配,则可调用search方法 , 与match方法类似 , 当任意位置匹配成功 , 则立即返回一个匹配对象 , 也可调用span()方法获取起止区间、调用group方法获得匹配文本串
import repattern = re.compile(r'\s[a-z]{2}')text1 = 'this is a re test'res = pattern.search(text1)print(res) #if res:print(res.group()) #isprint(res.span()) #(4, 7)pattern2 = re.compile(r'\s[a-z]{5}')text2 = '是的,this is a re test'print(pattern2.search(text2))#None
match和search均用于匹配单个结果 , 唯一区别在于前者是从起始位置开始匹配,而后者从任意位置匹配,匹配成功则返回一个match对象 。
全搜索:findall/finditer
几乎是最常用的正则表达式函数 , 用于寻找所有匹配的结果,例如在爬虫信息提取中 , 可非常方便地提取所有匹配字段
import repattern = 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 repattern = 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())"""isretest"""
当匹配模式串较为简单或者仅需单词调用时,上述所有方法也可直接调用re类函数,而无需事先编译 。此时各方法的第一个参数为模式串 。
import repattern = 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 retext = '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 retext = 'today is 2020-03-05'print(re.subn('-', '', text)) #('today is 20200305', 2)
分割:split
还可以调用正则表达式实现字符串的特定分割,相当于.split()方法的一个加强版,实现特定模式的分割,返回一个切割后的结果列表

推荐阅读