70.Python中re模塊中幾個常用正則表達式例說

常見的功能是找出字符串中所有模式字符串"findall",以匹配模式分割字符串"split",順序返回匹配結果"finditer",替換模式字符串"sub"。

import re
str="one0bone1cone20done3gone4hone5111lone6mone7none8pone90000rone10sone11tone12zone13"

#1.獲得字符串中符合模式的所有字符串。
p=re.compile(r'\d+')
mylist=p.findall(str)
print(" ".join(mylist))

#2.這裏可以出這麼一個題目:將字符串中所有數字提取出來,然後相加,算出結果。
total=0
for ele in range(0,len(mylist)):
    total=total+int(mylist[ele])#將字符串轉化爲證書
print(total)

#3.以p模式分割字符串,並輸出,
subs=re.split(p,str)
for sub in subs:
    print(sub,end=' ')#打印不換行,以某些符號代替,如' ','#"等。

#re.finditer返回的是迭代器,需要遍歷才能獲取數據。
#findall是返回一個列表。
iter=re.finditer(p,str)
for i in iter:
    print(i.group(),end=" ")

#爲了強化finditer,再舉一例,提取郵箱:
content = '''email:[email protected]
email:[email protected]
email:[email protected]
'''
pFinderiter=re.finditer(r'\d+@\w+.com',content)#可以直接用模式
for i in pFinderiter:
    print(i.group())#輸出用group.
    print(i.span())#這是跨度,在字符串什麼位置。

#將字符串中的模式替換掉。如' ','*'以及字符串
print(re.sub(p,'hello ',str))
print(re.sub(p,' ',str,4))#sub參數依次爲:模式,替換項,被替換項字符串,替換個數。

輸出結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章