import re st = 'asdfasxxixxdafqewxxlovexxsadawexxyouxxas' # . #點匹配除換行符外的任意字符 a0 = re.findall('xx.',st) #print(a0) #['xxi', 'xxd', 'xxl', 'xxs', 'xxy', 'xxa'] a1 = re.findall('xx..',st) #print(a1) #['xxix', 'xxlo', 'xxsa', 'xxyo', 'xxas'] # * #星匹配前面的一個字符一次或多次 b0 = re.findall('x*',st) #print(b0) #['', '', '', '', '', '', 'xx', '', 'xx', '', '', '', '', '', '', 'xx', '', '', '', '', 'xx', '', '', '', '', '', '', 'xx', '', '', '', 'xx', '', '', ''] # ? #問號匹配前面的一個字符0次或者1次 c0 = re.findall('x?',st) #print(c0) #['', '', '', '', '', '', 'x', 'x', '', 'x', 'x', '', '', '', '', '', '', 'x', 'x', '', '', '', '', 'x', 'x', '', '', '', '', '', '', 'x', 'x', '', '', '', 'x', 'x', '', '', ''] #貪心算法(點星)盡可能多的匹配 -- .* #盡可能長的匹配字符串 a = re.findall('xx.*xx',st) #print(a) #運行結果 #['xxixxdafqewxxlovexxsadawexxyouxx'] #非貪心算法(點星問號)少食多餐 -- .*? #返回列表 b = re.findall('xx.*?xx',st) #print(b) #運行結果 #['xxixx', 'xxlovexx', 'xxyouxx'] #非貪心算法(點星問號)少食多餐 -- .*? #返回列表 c = re.findall('xx(.*?)xx',st) #print(c) #運行結果 #['i', 'love', 'you'] # re.S 匹配換行符 ss = '''asdfasxxixxdafqewxxlove xxsadawexxyouxxas''' d = re.findall('xx(.*?)xx',ss) e = re.findall('xx(.*?)xx',ss,re.S) print("無re.S:%s\n有re.S:%s"%(d,e)) #運行結果 #無re.S:['i', 'sadawe'] #有re.S:['i', 'love\n', 'you']
貪心算法,非貪心算法
