a = 'xy123' b = re.findall('x...',a) print(b) # ['xy12']
*****:匹配前一个字符0次或者无限次
1 2 3 4
a = 'xyxy123' b = re.findall('x*',a) print(b) # ['x', '', 'x', '', '', '', '', '']
**?**:匹配前一个字符0次或者1次
1 2 3 4
a = 'xy123' b = re.findall('x?',a) print(b) # ['x', '', '', '', '', '']
**.***:贪心算法
1 2 3
b = re.findall('xx.*xx',secret_code) print(b) # ['xxIxxfasdjifja134xxlovexx23345sdfxxyouxx']
**.*?**:非贪心算法
1 2 3
c = re.findall('xx.*?xx',secret_code) print(c) # ['xxIxx', 'xxlovexx', 'xxyouxx']
**()**:括号内结果返回
1 2 3 4 5 6 7 8
d = re.findall('xx(.*?)xx',secret_code) print(d) for each in d: print(each) # ['I', 'love', 'you'] # I # love # you
re.S使得.的作用域包括换行符”\n”
1 2 3 4 5 6
s = '''sdfxxhello xxfsdfxxworldxxasdf'''
d = re.findall('xx(.*?)xx',s,re.S) print(d) # ['hello\n', 'world']
对比findall与search的区别
1 2 3 4 5 6 7
s2 = 'asdfxxIxx123xxlovexxdfd' f = re.search('xx(.*?)xx123xx(.*?)xx',s2).group(2) print(f) f2 = re.findall('xx(.*?)xx123xx(.*?)xx',s2) print(f2[0][1]) # love # love
s = '123rrrrr123' output = re.sub('123(.*?)123','123%d123'%789,s) print(output) # 123789123
例如我们需要将文档中的所有的png图片改变路径,即需要找到所有的.png结尾,再将其都加上路径,
1 2 3 4 5 6 7 8 9 10 11 12
import re
defmultiply(m): # Convert group 0 to an integer. v = m.group(0) print(v) # Multiply integer by 2. # ... Convert back into string and return it. print('basic/'+v) return'basic/'+v