python re的findall和finditer的區(qū)別詳解
python正則模塊re中findall和finditer兩者相似,但卻有很大區(qū)別。
兩者都可以獲取所有的匹配結(jié)果,這和search方法有著很大的區(qū)別,同時(shí)不同的是一個(gè)返回list,一個(gè)返回一個(gè)MatchObject類型的iterator
假設(shè)我們有這樣的數(shù)據(jù):其中數(shù)字代表電話號(hào),xx代表郵箱類型
content = ’’’email:[email protected]:[email protected]:[email protected]’’’
需求:(正則沒(méi)有分組)提取所有的郵箱信息
result_finditer = re.finditer(r'd+@w+.com', content)#由于返回的為MatchObject的iterator,所以我們需要迭代并通過(guò)MatchObject的方法輸出for i in result_finditer : print i.group()result_findall = re.findall(r'd+@w+.com', content)#返回一個(gè)[] 直接輸出or或者循環(huán)輸出print result_findallfor i in result_findall : print i
需求:(正則有分組)提取出來(lái)所有的電話號(hào)碼和郵箱類型
result_finditer = re.finditer(r'(d+)@(w+).com', content)#正則有兩個(gè)分組,我們需要分別獲取分區(qū),分組從0開(kāi)始,group方法不傳遞索引默認(rèn)為0,代表了整個(gè)正則的匹配結(jié)果for i in result_finditer : phone_no = i.group(1) email_type = i.group(2)result_findall = re.findall(r'(d+)@(w+).com', content)#此時(shí)返回的雖然為[],但不是簡(jiǎn)單的[],而是一個(gè)tuple類型的list #如:[(’12345678’, ’163’), (’2345678’, ’163’), (’345678’, ’163’)]for i in result_findall : phone_no = i[0] email_type = i[1]
命名分組和非命名分組的情況是一樣的。
findall注意點(diǎn):
1.當(dāng)正則沒(méi)有分組是返回的就是正則的匹配
re.findall(r'd+@w+.com', content)[’[email protected]’, ’[email protected]’, ’[email protected]’]
2.有一個(gè)分組返回的是分組的匹配而不是整個(gè)正則的匹配
re.findall(r'(d+)@w+.com', content)[’2345678’, ’2345678’, ’345678’]
3.多個(gè)分組時(shí)將分組裝到tuple中 返回
re.findall(r'(d+)@(w+).com', content)[(’2345678’, ’163’), (’2345678’, ’163’), (’345678’, ’163’)]
因此假如我們需要拿到整個(gè)正則和每個(gè)分組的匹配,使用findall我們需要將整個(gè)正則作為一個(gè)分組
re.findall(r'((d+)@(w+).com)', content)[(’[email protected]’, ’2345678’, ’163’), (’[email protected]’, ’2345678’, ’163’), (’[email protected]’, ’345678’, ’163’)]
而使用finditer我們無(wú)需手動(dòng)將整個(gè)正則用()括起來(lái)group()代表整個(gè)正則的匹配
實(shí)際中我們根據(jù)我們的需求選擇方法既可。
到此這篇關(guān)于python re的findall和finditer的區(qū)別詳解的文章就介紹到這了,更多相關(guān)python re的findall和finditer內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. ASP基礎(chǔ)知識(shí)VBScript基本元素講解2. jsp中sitemesh修改tagRule技術(shù)分享3. JSP servlet實(shí)現(xiàn)文件上傳下載和刪除4. React優(yōu)雅的封裝SvgIcon組件示例5. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)6. JavaWeb Servlet中url-pattern的使用7. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究8. 輕松學(xué)習(xí)XML教程9. asp(vbscript)中自定義函數(shù)的默認(rèn)參數(shù)實(shí)現(xiàn)代碼10. 詳解瀏覽器的緩存機(jī)制
