第一个问题:Python的re模块搜寻是贪婪模式还是非贪婪模式?
第二个问题:Python的re模块默认是搜寻方式是贪婪模式,请说明如何改为非贪婪模式?

通过实例分享:

下列程序使用搜寻模式'(jiet07){2,4}'搜寻字符串"jiet07jiet07jiet07jiet07"。

import redefsearchStr(pattern,msg): 	txt=re.search(pattern,msg)if txt==None:#搜索失败print("error",txt)else:#搜索成功print("success",txt.group()) msg="jiet07jiet07jiet07jiet07" pattern="(jiet07){2,4}" searchStr(pattern,msg)

结果

success jiet07jiet07jiet07jiet07

分析:由上述程序所设定的搜寻模式可知,2,3或4个jiet07重复就算找到了,可是Python执行结果是列出重复最多的字符串,即4次重复,这是Python的默认模式,这种模式又称贪婪(greedy)模式。

在正则表达式的搜寻模式最右边加上?符号。
下列程序会以非贪婪模式设计字符串”jiet07jiet07jiet07jiet07"的搜寻。

import redefsearchStr(pattern,msg): 	txt=re.search(pattern,msg)if txt==None:#搜索失败print("error",txt)else:#搜索成功print("success",txt.group()) msg="jiet07jiet07jiet07jiet07" pattern="(jiet07){2,4}?" searchStr(pattern,msg)

输出结果

success jiet07jiet07