1 """ 2 贪婪模式指 Python 里数量词默认是贪婪的,总是尝试匹配尽可能多的字符。非贪婪模 3 式与贪婪相反,总是尝试匹配尽可能少的字符,可以使用"*","?","+","{m,n}"后面加上?,使 4 贪婪变成非贪婪 5 """ 6 import re 7 v = re.match(r'(.+)(d+-d+-d+)','This is my tel:133-1234-1234') 8 print('----------贪婪模式---------') 9 print(v.group(1)) 10 print(v.group(2)) 11 print(v.groups()[0]) 12 print(v.groups()[1]) 13 v = re.match(r'(.+)(d+-d+-d+)','This is my tel:133-1234-1234') 14 print('----------非贪婪模式---------') 15 v = re.match(r'(.+?)(d+-d+-d+)','This is my tel:133-1234-1234') 16 print(v.group(1)) 17 print(v.group(2)) 18 19 print('**************实例2**************') 20 print('----------贪婪模式---------') 21 v = re.match(r'abc(d+)','abc123') 22 print(v.group(1)) 23 print('----------非贪婪模式---------') 24 v = re.match(r'abc(d+?)','abc123') 25 print(v.group(1))
1 ----------贪婪模式--------- 2 This is my tel:13 3 3-1234-1234 4 This is my tel:13 5 3-1234-1234 6 ----------非贪婪模式--------- 7 This is my tel: 8 133-1234-1234 9 **************实例2************** 10 ----------贪婪模式--------- 11 123 12 ----------非贪婪模式--------- 13 1