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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP