Python 中的匹配與搜尋


Python 根據正則表示式提供兩種不同的原始操作:匹配只檢查字串開頭的匹配,而搜尋檢查字串中任何位置的匹配(這是 Perl 的預設行為)。

示例

 即時演示

#!/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!!"
searchObj = re.search( r'dogs', line, re.M|re.I)
if searchObj:
   print "search --> searchObj.group() : ", searchObj.group()
else:
   print "Nothing found!!"

輸出

執行上述程式碼後,會產生以下結果 −

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

更新於: 2020-01-30

1K+ 次瀏覽

開啟你的

事業

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.