python re的findall和finditer的區別詳解
python正則模塊re中findall和finditer兩者相似,但卻有很大區別。
兩者都可以獲取所有的匹配結果,這和search方法有著很大的區別,同時不同的是一個返回list,一個返回一個MatchObject類型的iterator
假設我們有這樣的數據:其中數字代表電話號,xx代表郵箱類型
content = ’’’email:[email protected]:[email protected]:[email protected]’’’
需求:(正則沒有分組)提取所有的郵箱信息
result_finditer = re.finditer(r'd+@w+.com', content)#由于返回的為MatchObject的iterator,所以我們需要迭代并通過MatchObject的方法輸出for i in result_finditer : print i.group()result_findall = re.findall(r'd+@w+.com', content)#返回一個[] 直接輸出or或者循環輸出print result_findallfor i in result_findall : print i
需求:(正則有分組)提取出來所有的電話號碼和郵箱類型
result_finditer = re.finditer(r'(d+)@(w+).com', content)#正則有兩個分組,我們需要分別獲取分區,分組從0開始,group方法不傳遞索引默認為0,代表了整個正則的匹配結果for i in result_finditer : phone_no = i.group(1) email_type = i.group(2)result_findall = re.findall(r'(d+)@(w+).com', content)#此時返回的雖然為[],但不是簡單的[],而是一個tuple類型的list #如:[(’12345678’, ’163’), (’2345678’, ’163’), (’345678’, ’163’)]for i in result_findall : phone_no = i[0] email_type = i[1]
命名分組和非命名分組的情況是一樣的。
findall注意點:
1.當正則沒有分組是返回的就是正則的匹配
re.findall(r'd+@w+.com', content)[’[email protected]’, ’[email protected]’, ’[email protected]’]
2.有一個分組返回的是分組的匹配而不是整個正則的匹配
re.findall(r'(d+)@w+.com', content)[’2345678’, ’2345678’, ’345678’]
3.多個分組時將分組裝到tuple中 返回
re.findall(r'(d+)@(w+).com', content)[(’2345678’, ’163’), (’2345678’, ’163’), (’345678’, ’163’)]
因此假如我們需要拿到整個正則和每個分組的匹配,使用findall我們需要將整個正則作為一個分組
re.findall(r'((d+)@(w+).com)', content)[(’[email protected]’, ’2345678’, ’163’), (’[email protected]’, ’2345678’, ’163’), (’[email protected]’, ’345678’, ’163’)]
而使用finditer我們無需手動將整個正則用()括起來group()代表整個正則的匹配
實際中我們根據我們的需求選擇方法既可。
到此這篇關于python re的findall和finditer的區別詳解的文章就介紹到這了,更多相關python re的findall和finditer內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
