1.常用符号
. | 匹配任意字符 |
* | 匹配前一个字符0次或无限次 |
? | 匹配前一个字符0次或1次 |
.* | 贪心算法 |
.*? | 非贪心算法 |
() | 括号内的数据作为结果返回 |
.的用法
import re a = 'xy123' b = re.findall('x.',a) print b#['xy']
*的用法
import re a = 'xy123' b = re.findall('x*',a) print b#['x', '', '', '', '', '']
?的用法
import re a = 'xy123' b = re.findall('x.*?',a) print b#['x']
.*的用法
import re a = 'xy123xy456xy789xy987xy654xy321' print re.findall('xy.*xy', a) #['xy123xy456xy789xy987xy654xy'] print re.findall('xy.*?xy', a) #['xy123xy', 'xy789xy', 'xy654xy']
()的用法
import re a = 'xy123xy456xy789xy987xy654xy321' print re.findall('xy.*?xy', a)#['xy123xy', 'xy789xy', 'xy654xy'] print re.findall('xy(.*?)xy', a)#['123', '789', '654']
re.S的用法
import re a = '''xy123' xy456xy789xy987xy654xy321''' print re.findall('xy.*?xy', a)#['xy456xy', 'xy987xy'] print re.findall('xy(.*?)xy', a)#['456', '987'] print re.findall('xy.*?xy', a, re.S)#["xy123' xy", 'xy789xy', 'xy654xy'] print re.findall('xy(.*?)xy', a, re.S)#["123' ", '789', '654']
search用法
import re a = 'xy123xy456xy789xy987' print re.search('xy(.*?)xy456xy(.*?)xy', a).group()#xy123xy456xy789xy print re.search('xy(.*?)xy456xy(.*?)xy', a).group(1)#123 print re.search('xy(.*?)xy456xy(.*?)xy', a).group(2)#789 print re.findall('xy(.*?)xy456xy(.*?)xy', a)[0][0]#123
sub用法
import re a = 'xy123xy' print re.sub('xy(.*?)xy','XY%dXY'%321, a)#XY321XY
匹配数字
import re a = 'xy123xy' print re.findall('(d+)', a)#['123']