亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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的開始位置匹配, 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)文章

最新評(píng)論