1、search:与findall用法完全一致,不一样的地方在于search匹配一次就结束
print(re.search('alex','alex say hello alex').group()) alex
匹配的是一个对象,拿到这个值,需要调group
2、match:match代表从头匹配
print(re.match('alex','alex say hello alex').group()) print(re.match('alex',' alex say hello alex').group()) 相当于: print(re.search('^alex','alex say hello alex').group())
3、split
print(re.split(':','root:x:0:0:/root::/bin/bash')) ['root', 'x', '0', '0', '/root', '', '/bin/bash']
4、sub---替换
print(re.sub('alex','SB','alex say i have on telsa my name is alex',1)) print(re.subn('alex','SB','alex say i have on telsa my name is alex')) #后面1意思是替换一次,默认全部替换; #subn:可以显示替换了几次: SB say i have on telsa my name is alex ('SB say i have on telsa my name is SB', 2)
print(re.sub(r'(w+)(W+)(w+)(W+)(w+)',r'52341','alex-love: SB')) print(re.sub(r'^al',r'AAAAAAAAA','alex-love: SB alex')) SB-love: alex AAAAAAAAAex-love: SB alex
5、正则表达式重用
print(re.findall('^alex','alex say hello alex')) print(re.search('^alex','alex say hello alex')) obj=re.compile(r'^alex') print(obj.findall('alex say hello alex')) print(obj.search('alex say hello alex').group())
6、补充:
print(re.findall(r'<.*?>.*?</.*?>','<h1>hello</h1>')) print(re.findall(r'<(.*?)>.*?</(.*?)>','<h1>hello</h1>')) print(re.findall(r'<(.*?)>.*?</(1)>','<h1>hello</h1>')) print(re.findall(r'<(?P<k>.*?)>.*?</(?P=k)>','<h1>hello</h1>')) ['<h1>hello</h1>'] [('h1', 'h1')] [('h1', 'h1')] ['h1'] 取所有 取分组 同上 取k
7、取数字
print(re.findall('-?d+.?d*',"1-12*(60+(-40.35/5)-(-4*3))")) ['1', '-12', '60', '-40.35', '5', '-4', '3']
print(re.findall('-?d+',"1-12*(60+(-40.35/5)-(-4*3))")) print(re.findall('-?d+.d+',"1-12*(60+(-40.35/5)-(-4*3))")) print(re.findall('-?d+.d+|(-?d+)',"1-12*(60+(-40.35/5)-(-4*3))")) #只留下整数 print(re.findall('(-?d+.d+)|-?d+',"1-12*(60+(-40.35/5)-(-4*3))")) #只留下小数
expression='1-2*((60+2*(-3-40.0/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))' print(re.search(r'(([-+*/]?d+.?d*)+)',expression).group()) #取第一个括号内容 print(eval(expression)) 牛逼