贪婪模式非贪婪模式

贪婪模式:

正则引擎默认是贪婪模式,尽可能多的匹配字符。

非贪婪模式

与贪婪模式相反,尽可能少的匹配字符

在表示数量的“*”,“?”,“+”,“{m,n}”符号后面加上?,使贪婪变成非贪婪。

示例:贪婪模式演示

rs = re.findall("hello\d*", "hello12345") #任意多个数字
print(rs)
rs = re.findall("hello\d+", "hello12345")#至少出现一次数字
print(rs)
rs = re.findall("hello\d?", "hello12345")#至多出现一次数字
print(rs)
rs = re.findall("hello\d{2,}", "hello12345") #至少出现2次数字
print(rs)
rs = re.findall("hello\d{1,3}","hello12345") #出现1到3次数字
print(rs)

运行结果:

[‘hello12345’]
[‘hello12345’]
[‘hello1’]
[‘hello12345’]
[‘hello123’]
从运行结果看每个正则表示都尽可能多的匹配了字符

示例:非贪婪模式,在贪婪模式的正则表达式表示数量的符号后边添加?切换为非贪婪模式

rs = re.findall("hello\d*?", "hello12345") #任意多个数字,也可以没有
print(rs)
rs = re.findall("hello\d+?", "hello12345") #至少一个,匹配了1个
print(rs)
rs = re.findall("hello\d??", "hello12345") #至多一个,可以没有
print(rs)
rs = re.findall("hello\d{2,}?", "hello12345") #最少两个,匹配了两个
print(rs)
rs = re.findall('hello\d{1,3}?', 'hello12345') #1到3个,匹配了1个
print(rs)

运行结果:

[‘hello’]
[‘hello1’]
[‘hello’]
[‘hello12’]
[‘hello1’]

猜你喜欢

转载自blog.csdn.net/lildn/article/details/114528813