Python - 搜尋和匹配



在使用正則表示式時,有兩個經常混淆的基本操作,但它們的顯著差異。re.match() 只檢查字串開頭的匹配項,而 re.search() 檢查字串中任何位置的匹配項。這在文字處理中扮演了重要角色,因為我們常常必須編寫正確的正則表示式,才能檢索出情感分析的文字塊,例如。

import re

if  re.search("tor", "Tutorial"):
        print "1. search result found anywhere in the string"
        
if re.match("Tut", "Tutorial"):
         print "2. Match with beginning of string" 
         
if not re.match("tor", "Tutorial"):
        print "3. No match with match if not beginning" 


        
# Search as Match
        
if  not re.search("^tor", "Tutorial"):
        print "4. search as match"


當我們執行以上程式時,我們獲得以下輸出 −

1. search result found anywhere in the string
2. Match with beginning of string
3. No match with match if not beginning
4. search as match
廣告
© . All rights reserved.