Python中正則表達(dá)式match()、search()函數(shù)及match()和search()的區(qū)別詳解
match()和search()都是python中的正則匹配函數(shù),那這兩個(gè)函數(shù)有何區(qū)別呢?
match()函數(shù)只檢測(cè)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á)式的匹配,在我看來這種方式更簡(jiǎn)潔,不過不適合大型程序的編寫,后期維護(hù)可能會(huì)產(chǎn)生困難,不過編寫一些小腳本完全可以勝任。
Python中正則表達(dá)式search()函數(shù)
search函數(shù)和match函數(shù)有點(diǎn)類似,都可以匹配模式,但是match和search函數(shù)也有區(qū)別,而且區(qū)別很大,match函數(shù)只能夠字符串的開始位置開始匹配,而search是可以匹配字符串的任意位置,但也是返回找到的第一個(gè)匹配的模式。我們通過例子來了解這倆之間的區(qū)別吧。
相關(guān)文章
UBB 轉(zhuǎn)換函數(shù)演示 (經(jīng)典論壇)
[綠色]UBB 轉(zhuǎn)換函數(shù)演示 (經(jīng)典論壇)...2006-08-08手機(jī)號(hào)碼驗(yàn)證方法(正則驗(yàn)證)
這篇文章主要介紹了手機(jī)號(hào)碼驗(yàn)證方法(正則驗(yàn)證),在文章中還給大家補(bǔ)充了最新手機(jī)號(hào)的驗(yàn)證正則表達(dá)式,需要的朋友可以參考下2017-02-02