match()和search()都是python中的正則匹配函數(shù),那這兩個(gè)函數(shù)有何區(qū)別呢?
match()函數(shù)只檢測RE是不是在string的開始位置匹配, search()會(huì)掃描整個(gè)string查找匹配, 也就是說match()只有在0位置匹配成功的話才有返回,如果不是開始位置匹配成功的話,match()就返回none
例如:
#! /usr/bin/env python # -*- coding=utf-8 -*- import re text = 'pythontab' m = re.match(r"\w+", text) if m: print m.group(0) else: print 'not match'
結(jié)果是:pythontab
而:
#! /usr/bin/env python # -*- coding=utf-8 -*- # import re text = '@pythontab' m = re.match(r"\w+", text) if m: print m.group(0) else: print 'not match'
結(jié)果是:not match
search()會(huì)掃描整個(gè)字符串并返回第一個(gè)成功的匹配
例如:
#! /usr/bin/env python # -*- coding=utf-8 -*- # import re text = 'pythontab' m = re.search(r"\w+", text) if m: print m.group(0) else: print 'not match'
結(jié)果是:pythontab
那這樣呢:
#! /usr/bin/env python # -*- coding=utf-8 -*- # import re text = '@pythontab' m = re.search(r"\w+", text) if m: print m.group(0) else: print 'not match'
結(jié)果是:pythontab
總結(jié):
Python中正則表達(dá)式match()函數(shù)
如果不創(chuàng)建pattern對(duì)象,我們使用match函數(shù)可以直接進(jìn)行正則表達(dá)式的匹配,在我看來這種方式更簡潔,不過不適合大型程序的編寫,后期維護(hù)可能會(huì)產(chǎn)生困難,不過編寫一些小腳本完全可以勝任。
Python中正則表達(dá)式search()函數(shù)
search函數(shù)和match函數(shù)有點(diǎn)類似,都可以匹配模式,但是match和search函數(shù)也有區(qū)別,而且區(qū)別很大,match函數(shù)只能夠字符串的開始位置開始匹配,而search是可以匹配字符串的任意位置,但也是返回找到的第一個(gè)匹配的模式。我們通過例子來了解這倆之間的區(qū)別吧。
標(biāo)簽:三亞 咸陽 鞍山 梅州 池州 恩施 六安 綿陽
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Python中正則表達(dá)式match()、search()函數(shù)及match()和search()的區(qū)別詳解》,本文關(guān)鍵詞 Python,中,正則,表達(dá)式,match,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。