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

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

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

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

match()函數(shù)只檢測RE是不是在string的開始位置匹配, search()會掃描整個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()會掃描整個字符串并返回第一個成功的匹配

例如:

#! /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中正則表達式match()函數(shù)

如果不創(chuàng)建pattern對象,我們使用match函數(shù)可以直接進行正則表達式的匹配,在我看來這種方式更簡潔,不過不適合大型程序的編寫,后期維護可能會產(chǎn)生困難,不過編寫一些小腳本完全可以勝任。

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

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


相關(guān)文章

最新評論