1. 程式人生 > >New-Python-模塊之re其他

New-Python-模塊之re其他

earch code eval aaa alex oot com arch 默認

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其他