python正则表达式01--贪心算法和非贪心算法findall()

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']

贪心算法,非贪心算法

猜你喜欢

转载自www.cnblogs.com/chillytao-suiyuan/p/9073585.html