国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Regex > 正文

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

2020-03-16 21:04:16
字體:
來源:轉載
供稿:網友
這篇文章主要介紹了Python中正則表達式match()、search()函數及match()和search()的區別詳解的相關資料,需要的朋友可以參考下
 

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

match()函數只檢測RE是不是在string的開始位置匹配, search()會掃描整個string查找匹配, 也就是說match()只有在0位置匹配成功的話才有返回,如果不是開始位置匹配成功的話,match()就返回none

例如:
 

  1. #! /usr/bin/env python 
  2. # -*- coding=utf-8 -*- 
  3. import re 
  4. text = 'pythontab' 
  5. m = re.match(r"/w+", text) 
  6. if m:  
  7.   print m.group(0) 
  8. else
  9.   print 'not match' 
?

結果是:pythontab

而:
 

  1. #! /usr/bin/env python 
  2. # -*- coding=utf-8 -*- 
  3. # 
  4. import re 
  5. text = '@pythontab' 
  6. m = re.match(r"/w+", text) 
  7. if m:  
  8.   print m.group(0) 
  9. else
  10.   print 'not match' 
?

結果是:not match

search()會掃描整個字符串并返回第一個成功的匹配

例如:
 

  1. #! /usr/bin/env python 
  2. # -*- coding=utf-8 -*- 
  3. # 
  4. import re 
  5. text = 'pythontab' 
  6. m = re.search(r"/w+", text) 
  7. if m:  
  8.   print m.group(0) 
  9. else
  10.   print 'not match' 
?

結果是:pythontab

那這樣呢:
 

  1. #! /usr/bin/env python 
  2. # -*- coding=utf-8 -*- 
  3. # 
  4. import re 
  5. text = '@pythontab' 
  6. m = re.search(r"/w+", text) 
  7. if m:  
  8.   print m.group(0) 
  9. else
  10.   print 'not match' 
?

結果是:pythontab

總結:

Python中正則表達式match()函數

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

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

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

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

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


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 庆云县| 祁东县| 青神县| 绥滨县| 资阳市| 吐鲁番市| 岐山县| 尤溪县| 永靖县| 亚东县| 莆田市| 法库县| 泗洪县| 丰都县| 彩票| 无为县| 蕲春县| 新密市| 资中县| 崇义县| 金坛市| 治多县| 丹棱县| 宝山区| 麟游县| 云霄县| 体育| 乌鲁木齐县| 光山县| 巴彦淖尔市| 柳林县| 临武县| 尼木县| 平阳县| 佳木斯市| 兴仁县| 肇州县| 海南省| 上饶市| 峨眉山市| 上虞市|