首頁  >  文章  >  後端開發  >  簡訴Python Re模組中re.search和re.match的區別

簡訴Python Re模組中re.search和re.match的區別

Tomorin
Tomorin原創
2018-08-15 13:55:143221瀏覽

先前的兩篇文章《python re.match函數是什麼,了解python match函數的使用》,《Python中的python re.search方法詳解》,我們介紹了Python中Re模組的match模組和search模組,這邊文章就是與前兩篇連動說明re.search和re.match的區別

什麼是re.search

參見文章《Python中的python re.search方法詳解》

什麼是re.match:

參考文章:《python re.match函數是什麼,了解python match函數的使用》

那麼re.search和re.match的差別是什麼

簡而言之是re.match只符合字串的開始,如果字串開始不符合正規表示式,則匹配失敗,函數傳回None;而re.search則匹配整個字串,直到找到一個符合

實例:

#!/usr/bin/python
import re
line = "Cats are smarter than dogs"; 
matchObj = re.match( r'dogs', line, re.M|re.I)
if matchObj:  
   print "match --> matchObj.group() : ", matchObj.group()
else:   print "No match!!"
matchObj = re.search( r'dogs', line, re.M|re.I)
    if matchObj: 
      print "search --> matchObj.group() : ", matchObj.group()
    else:   
       print "No match!!"

以上實例運行結果如下:

No match!!
search --> matchObj.group() :  dogs


以上是簡訴Python Re模組中re.search和re.match的區別的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn