码迷,mamicode.com
首页 > 编程语言 > 详细

New-Python-模块之re其他

时间:2017-10-28 13:00:51      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:style   结束   log   group   lsa   res   hello   com   取数   

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\5\2\3\4\1,alex-love: SB))
print(re.sub(r^al,rAAAAAAAAA,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))   牛逼

 

New-Python-模块之re其他

标签:style   结束   log   group   lsa   res   hello   com   取数   

原文地址:http://www.cnblogs.com/guoxiangqian/p/7746339.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!