python正則表達(dá)式re模塊詳解
更新時(shí)間:2014年06月25日 11:04:02 投稿:hebedich
re 模塊包含對(duì)正則表達(dá)式的支持,因?yàn)樵?jīng)系統(tǒng)學(xué)習(xí)過(guò)正則表達(dá)式,所以基礎(chǔ)內(nèi)容略過(guò),直接看 python 對(duì)于正則表達(dá)式的支持。
快速入門(mén)
import re pattern = 'this' text = 'Does this text match the pattern?' match = re.search(pattern, text) s = match.start() e = match.end() print('Found "{0}"\nin "{1}"'.format(match.re.pattern, match.string)) print('from {0} to {1} ("{2}")'.format( s, e, text[s:e]))
執(zhí)行結(jié)果:
#python re_simple_match.py Found "this" in "Does this text match the pattern?" from 5 to 9 ("this") import re # Precompile the patterns regexes = [ re.compile(p) for p in ('this', 'that')] text = 'Does this text match the pattern?' print('Text: {0}\n'.format(text)) for regex in regexes: if regex.search(text): result = 'match!' else: result = 'no match!' print('Seeking "{0}" -> {1}'.format(regex.pattern, result))
執(zhí)行結(jié)果:
#python re_simple_compiled.py Text: Does this text match the pattern? Seeking "this" -> match! Seeking "that" -> no match! import re text = 'abbaaabbbbaaaaa' pattern = 'ab' for match in re.findall(pattern, text): print('Found "{0}"'.format(match))
執(zhí)行結(jié)果:
#python re_findall.py Found "ab" Found "ab" import re text = 'abbaaabbbbaaaaa' pattern = 'ab' for match in re.finditer(pattern, text): s = match.start() e = match.end() print('Found "{0}" at {1}:{2}'.format(text[s:e], s, e))
執(zhí)行結(jié)果:
#python re_finditer.py Found "ab" at 0:2 Found "ab" at 5:7
相關(guān)文章
python3 批量獲取對(duì)應(yīng)端口服務(wù)的實(shí)例
今天小編就為大家分享一篇python3 批量獲取對(duì)應(yīng)端口服務(wù)的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-07-07Python3利用Dlib實(shí)現(xiàn)攝像頭實(shí)時(shí)人臉檢測(cè)和平鋪顯示示例
這篇文章主要介紹了Python3利用Dlib實(shí)現(xiàn)攝像頭實(shí)時(shí)人臉檢測(cè)和平鋪顯示示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-02-02opencv之顏色過(guò)濾只留下圖片中的紅色區(qū)域操作
這篇文章主要介紹了opencv之顏色過(guò)濾只留下圖片中的紅色區(qū)域操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-06-06利用Python實(shí)現(xiàn)學(xué)生信息管理系統(tǒng)的完整實(shí)例
這篇文章主要給大家介紹了關(guān)于如何利用Python實(shí)現(xiàn)學(xué)生信息管理系統(tǒng)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12解決pyecharts在jupyter notebook中使用報(bào)錯(cuò)問(wèn)題
這篇文章主要介紹了解決pyecharts在jupyter notebook中使用報(bào)錯(cuò)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-06-06