糖尿病康复,内容丰富有趣,生活中的好帮手!
糖尿病康复 > 贪婪模式非贪婪模式

贪婪模式非贪婪模式

时间:2019-04-30 04:08:52

相关推荐

贪婪模式非贪婪模式

贪婪模式:

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

非贪婪模式

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

在表示数量的“*”,“?”,“+”,“{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’]

如果觉得《贪婪模式非贪婪模式》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。