欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python中正則表達(dá)式match()、search()函數(shù)及match()和search()的區(qū)別詳解

 更新時(shí)間:2015年09月25日 10:15:13   投稿:mrr  
這篇文章主要介紹了Python中正則表達(dá)式match()、search()函數(shù)及match()和search()的區(qū)別詳解的相關(guān)資料,需要的朋友可以參考下

match()和search()都是python中的正則匹配函數(shù),那這兩個(gè)函數(shù)有何區(qū)別呢?

match()函數(shù)只檢測(cè)RE是不是在string的開(kāi)始位置匹配, search()會(huì)掃描整個(gè)string查找匹配, 也就是說(shuō)match()只有在0位置匹配成功的話才有返回,如果不是開(kāi)始位置匹配成功的話,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á)式的匹配,在我看來(lái)這種方式更簡(jiǎn)潔,不過(guò)不適合大型程序的編寫(xiě),后期維護(hù)可能會(huì)產(chǎn)生困難,不過(guò)編寫(xiě)一些小腳本完全可以勝任。

Python中正則表達(dá)式search()函數(shù)

search函數(shù)和match函數(shù)有點(diǎn)類似,都可以匹配模式,但是match和search函數(shù)也有區(qū)別,而且區(qū)別很大,match函數(shù)只能夠字符串的開(kāi)始位置開(kāi)始匹配,而search是可以匹配字符串的任意位置,但也是返回找到的第一個(gè)匹配的模式。我們通過(guò)例子來(lái)了解這倆之間的區(qū)別吧。


相關(guān)文章

最新評(píng)論